Compare commits
17
Commits
v0.2.0
...
22077514fe
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22077514fe | ||
|
|
6761f2d9ea | ||
|
|
18ff32b5ce | ||
|
|
67530d35e9 | ||
|
|
26ca1b90a2 | ||
|
|
c529b04ff0 | ||
|
|
36df4a46b9 | ||
|
|
51e90b6127 | ||
|
|
063ad8a3e1 | ||
|
|
68cd9fc4f9 | ||
|
|
c56046469e | ||
|
|
a0d1ec2feb | ||
|
|
3b21fc3aa6 | ||
|
|
90e54ec295 | ||
|
|
df4d58a279 | ||
|
|
837367047c | ||
|
|
600373dc61 |
No files matched your search
@@ -9,6 +9,8 @@
|
|||||||
!compat/
|
!compat/
|
||||||
!agent/
|
!agent/
|
||||||
!patcher/
|
!patcher/
|
||||||
|
!mod-tools/
|
||||||
|
!gradle-plugin/
|
||||||
!docker/
|
!docker/
|
||||||
**/build/
|
**/build/
|
||||||
**/.gradle/
|
**/.gradle/
|
||||||
@@ -15,12 +15,12 @@ jobs:
|
|||||||
include:
|
include:
|
||||||
# One entry per supported version; add older Steam version branches
|
# One entry per supported version; add older Steam version branches
|
||||||
# (e.g. pz_version 42.19, steam_branch 42.19) to keep them building.
|
# (e.g. pz_version 42.19, steam_branch 42.19) to keep them building.
|
||||||
- pz_version: "42.21"
|
- pz_version: "42"
|
||||||
steam_branch: public
|
steam_branch: public
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
with:
|
with:
|
||||||
# release.sh derives the version from the newest v* tag
|
# release.sh derives the version from the v* tags
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Build and verify
|
- name: Build and verify
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Publishes the mod API, the mod tools, and the Gradle plugin to the Gitea Maven registry
|
||||||
|
# (https://git.security-command.org/api/packages/overlord/maven) for every release tag.
|
||||||
|
# Pre-release tags (containing "-") are tested but not published (see ci/publish.sh).
|
||||||
|
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with package
|
||||||
|
# write access), the same as the image release.
|
||||||
|
name: publish
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
maven:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
|
with:
|
||||||
|
# publish.sh derives the version from the v* tag on HEAD
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "25"
|
||||||
|
|
||||||
|
# The tests run without the registry credentials; only the publish step gets them.
|
||||||
|
- name: Test
|
||||||
|
run: ci/publish.sh test
|
||||||
|
|
||||||
|
- name: Publish
|
||||||
|
env:
|
||||||
|
ORG_GRADLE_PROJECT_giteaUsername: ${{ secrets.REGISTRY_USER }}
|
||||||
|
ORG_GRADLE_PROJECT_giteaPassword: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
run: ci/publish.sh publish
|
||||||
@@ -1,12 +1,16 @@
|
|||||||
# Publishes an image for every new Steam build of each supported Project Zomboid
|
# Publishes an image for every new Project Zomboid version (hotfixes included) of each
|
||||||
# version. Immutable tags are never overwritten (see ci/release.sh).
|
# matrix entry and every new ZomboidForge release; full version tags are never overwritten
|
||||||
|
# (see ci/release.sh).
|
||||||
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with
|
# Requires the repository secrets REGISTRY_USER and REGISTRY_TOKEN (a token with
|
||||||
# package write access) and a runner with a Docker (or Podman) CLI.
|
# package write access) and a runner with a Docker (or Podman) CLI.
|
||||||
name: release
|
name: release
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
# Every 2.5 hours; cron cannot divide a day into 2.5-hour steps, so the gap
|
||||||
|
# from 22:30 to 00:00 is 1.5 hours.
|
||||||
schedule:
|
schedule:
|
||||||
- cron: "0 */6 * * *"
|
- cron: "0 0,5,10,15,20 * * *"
|
||||||
|
- cron: "30 2,7,12,17,22 * * *"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
@@ -16,13 +20,13 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
include:
|
include:
|
||||||
- pz_version: "42.21"
|
- pz_version: "42"
|
||||||
steam_branch: public
|
steam_branch: public
|
||||||
latest: "true"
|
latest: "true"
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
with:
|
with:
|
||||||
# release.sh derives the version from the newest v* tag
|
# release.sh derives the version from the v* tags
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Log in to the registry
|
- name: Log in to the registry
|
||||||
@@ -39,3 +43,8 @@ jobs:
|
|||||||
PUBLISH: "true"
|
PUBLISH: "true"
|
||||||
LATEST: ${{ matrix.latest }}
|
LATEST: ${{ matrix.latest }}
|
||||||
run: ci/release.sh
|
run: ci/release.sh
|
||||||
|
|
||||||
|
# Removes the stored registry token, also when a step failed, in case the runner is reused.
|
||||||
|
- name: Log out of the registry
|
||||||
|
if: always()
|
||||||
|
run: docker logout git.security-command.org
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
*.md
|
*.md
|
||||||
!README.md
|
!README.md
|
||||||
|
!MOD_DEVELOPMENT.md
|
||||||
lib
|
lib
|
||||||
.*/
|
.*/
|
||||||
!.gitea/
|
!.gitea/
|
||||||
|
|||||||
+49
-9
@@ -6,6 +6,10 @@
|
|||||||
# podman build --platform linux/amd64 -t zomboidforge .
|
# podman build --platform linux/amd64 -t zomboidforge .
|
||||||
# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ...
|
# podman build --build-arg PZ_BRANCH=42.19 --build-arg PZ_VERSION=42.19 ...
|
||||||
#
|
#
|
||||||
|
# The stage game-version (--target game-version) downloads only the server jar of
|
||||||
|
# PZ_BRANCH and writes its game version to /game-version; ci/release.sh uses it to
|
||||||
|
# name the image before the full build.
|
||||||
|
#
|
||||||
# Build arguments:
|
# Build arguments:
|
||||||
# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...)
|
# PZ_BRANCH Steam branch of app 380870: public, unstable, or a version branch (42.19, ...)
|
||||||
# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded
|
# PZ_VERSION Expected Project Zomboid version; the build fails when the downloaded
|
||||||
@@ -14,7 +18,8 @@
|
|||||||
# files with steamcmd's newer copies
|
# files with steamcmd's newer copies
|
||||||
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
|
# FORGE_VERSION ZomboidForge version (jar manifest, image label); set by ci/release.sh.
|
||||||
# Default: 0.0.0-prerelease
|
# Default: 0.0.0-prerelease
|
||||||
# STEAM_BUILDID Image label only; set by ci/release.sh
|
# STEAM_BUILDID Image label; in the stage game-version it keeps the cached result until
|
||||||
|
# Steam publishes a new build. Set by ci/release.sh
|
||||||
# DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
|
# DISABLED_PATCHES Comma-separated simple class names of build-time patches to skip
|
||||||
# (debug builds only; ci/release.sh never sets it)
|
# (debug builds only; ci/release.sh never sets it)
|
||||||
|
|
||||||
@@ -24,8 +29,11 @@ ARG STEAMCLIENT=bundled
|
|||||||
ARG FORGE_VERSION="0.0.0-prerelease"
|
ARG FORGE_VERSION="0.0.0-prerelease"
|
||||||
ARG STEAM_BUILDID=""
|
ARG STEAM_BUILDID=""
|
||||||
|
|
||||||
|
# Base images are pinned by digest; the tag in front of the digest is for readers only.
|
||||||
|
# The same steamcmd image is in ci/steam-buildid.sh and the Gradle plugin's DownloadGame.
|
||||||
|
|
||||||
# --- Stage 1: vanilla dedicated server -----------------------------------------
|
# --- Stage 1: vanilla dedicated server -----------------------------------------
|
||||||
FROM docker.io/steamcmd/steamcmd:debian-13 AS server
|
FROM docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d AS server
|
||||||
|
|
||||||
# steamcmd updates itself on its first run. This runs in its own layer so the
|
# steamcmd updates itself on its first run. This runs in its own layer so the
|
||||||
# update is cached and separate from the app installation.
|
# update is cached and separate from the app installation.
|
||||||
@@ -36,8 +44,8 @@ ARG STEAMCLIENT
|
|||||||
COPY docker/install-server.sh /usr/local/bin/install-server
|
COPY docker/install-server.sh /usr/local/bin/install-server
|
||||||
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
|
RUN install-server /server "${PZ_BRANCH}" "${STEAMCLIENT}"
|
||||||
|
|
||||||
# --- Stage 2: ZomboidForge build and server jar patching -----------------------
|
# --- Stage 2: ZomboidForge sources and Gradle -----------------------------------
|
||||||
FROM docker.io/library/eclipse-temurin:25-jdk AS build
|
FROM docker.io/library/eclipse-temurin:25-jdk@sha256:8c0a84ea11c8f6ed52600fc19f1040121f2a162998e9f50a5faebbbad9172dcc AS sources
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
# Gradle distribution download, cached independently of the sources.
|
# Gradle distribution download, cached independently of the sources.
|
||||||
@@ -51,6 +59,37 @@ COPY core core
|
|||||||
COPY compat compat
|
COPY compat compat
|
||||||
COPY agent agent
|
COPY agent agent
|
||||||
COPY patcher patcher
|
COPY patcher patcher
|
||||||
|
COPY mod-tools mod-tools
|
||||||
|
COPY gradle-plugin gradle-plugin
|
||||||
|
|
||||||
|
# --- Game version of a Steam branch, from its server jar alone ------------------
|
||||||
|
# Not part of the image; built on its own by ci/release.sh.
|
||||||
|
FROM sources AS game-version
|
||||||
|
|
||||||
|
# DepotDownloader downloads single files of a depot; steamcmd only whole apps.
|
||||||
|
ADD --checksum=sha256:a999dec66b4850fc961bd50366696d23c2d0fad7b18790e6a5647b2f19097a53 \
|
||||||
|
https://github.com/SteamRE/DepotDownloader/releases/download/DepotDownloader_3.4.0/DepotDownloader-linux-x64.zip \
|
||||||
|
/opt/depotdownloader/depotdownloader.zip
|
||||||
|
RUN cd /opt/depotdownloader \
|
||||||
|
&& jar xf depotdownloader.zip \
|
||||||
|
&& chmod +x DepotDownloader \
|
||||||
|
&& rm depotdownloader.zip
|
||||||
|
|
||||||
|
# FORGE_VERSION only keeps Gradle from asking git (not in this stage) for the version.
|
||||||
|
ARG PZ_BRANCH
|
||||||
|
ARG STEAM_BUILDID
|
||||||
|
ARG FORGE_VERSION
|
||||||
|
RUN echo java/projectzomboid.jar > /tmp/files \
|
||||||
|
&& /opt/depotdownloader/DepotDownloader \
|
||||||
|
-app 380870 -depot 380871 -branch "${PZ_BRANCH}" -filelist /tmp/files -dir /pz \
|
||||||
|
&& ./gradlew --no-daemon --quiet \
|
||||||
|
-Ppz.jar=/pz/java/projectzomboid.jar \
|
||||||
|
-Pversion=${FORGE_VERSION} \
|
||||||
|
:patcher:printGameVersion > /game-version
|
||||||
|
|
||||||
|
# --- Stage 3: ZomboidForge build and server jar patching -----------------------
|
||||||
|
FROM sources AS build
|
||||||
|
|
||||||
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
|
COPY --from=server /server/java/projectzomboid.jar /pz/projectzomboid.jar
|
||||||
|
|
||||||
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
|
# An empty PZ_VERSION keeps pz.version from gradle.properties. FORGE_VERSION always has a
|
||||||
@@ -63,10 +102,10 @@ RUN ./gradlew --no-daemon \
|
|||||||
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
|
${PZ_VERSION:+-Ppz.version=${PZ_VERSION}} \
|
||||||
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
|
${FORGE_VERSION:+-Pversion=${FORGE_VERSION}} \
|
||||||
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
|
${DISABLED_PATCHES:+-Pzf.disabledPatches=${DISABLED_PATCHES}} \
|
||||||
build :patcher:patchServerJar
|
build -x :gradle-plugin:test :patcher:patchServerJar
|
||||||
|
|
||||||
# --- Stage 3: runtime ------------------------------------------------------------
|
# --- Stage 4: runtime ------------------------------------------------------------
|
||||||
FROM docker.io/library/debian:trixie-slim
|
FROM docker.io/library/debian:trixie-slim@sha256:a99cfc517144bc59b1978475ec53b46ecabec7e43635402ee5b77cc54cd1b20a
|
||||||
|
|
||||||
# ca-certificates: required by steamclient.so to connect to Steam.
|
# ca-certificates: required by steamclient.so to connect to Steam.
|
||||||
# sqlite3: the entrypoint checks the admin account in the server database.
|
# sqlite3: the entrypoint checks the admin account in the server database.
|
||||||
@@ -76,9 +115,10 @@ RUN apt-get update \
|
|||||||
&& apt-get install --yes --no-install-recommends ca-certificates sqlite3 \
|
&& apt-get install --yes --no-install-recommends ca-certificates sqlite3 \
|
||||||
&& rm --recursive --force /var/lib/apt/lists/*
|
&& rm --recursive --force /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# /forge/mods holds Java mods (one folder per mod); usually a mounted directory.
|
||||||
RUN useradd --create-home --uid 1000 pz \
|
RUN useradd --create-home --uid 1000 pz \
|
||||||
&& mkdir /data \
|
&& mkdir --parents /data /forge/mods \
|
||||||
&& chown pz:pz /data
|
&& chown --recursive pz:pz /data /forge
|
||||||
|
|
||||||
COPY --from=server /server /opt/pz
|
COPY --from=server /server /opt/pz
|
||||||
COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/projectzomboid.jar
|
COPY --from=build /src/patcher/build/server/projectzomboid.jar /opt/pz/java/projectzomboid.jar
|
||||||
|
|||||||
@@ -0,0 +1,309 @@
|
|||||||
|
# Mod development
|
||||||
|
|
||||||
|
How to write a server-side Java mod for ZomboidForge. Installing mods on a server is
|
||||||
|
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.
|
||||||
|
|
||||||
|
`settings.gradle.kts`:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
maven("https://git.security-command.org/api/packages/overlord/maven")
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
version = "1.2.0"
|
||||||
|
|
||||||
|
zomboidForge {
|
||||||
|
id = "shop"
|
||||||
|
entrypoint = "com.example.shop.ShopMod"
|
||||||
|
game("42") // only when the mod uses game classes
|
||||||
|
dependsOn("economy", "2.1") // other mods: id and minimum version
|
||||||
|
}
|
||||||
|
|
||||||
|
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 { }`
|
||||||
|
|
||||||
|
| Setting | Default | Meaning |
|
||||||
|
|--------------------------|------------------------------------------|-----------------------------------------------------------------------------------|
|
||||||
|
| `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 |
|
||||||
|
| `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 |
|
||||||
|
| `previousIds(...)` | none | earlier ids of the mod; their storage moves to the current id |
|
||||||
|
| `gameJar` | see below | the `projectzomboid.jar` to compile and check against |
|
||||||
|
| `steamBranch` | `public` | Steam branch for the download: `public`, `unstable`, or a version such as `42.19` |
|
||||||
|
| `serverImage` | the ZomboidForge image, `latest` | image for `runServer` |
|
||||||
|
| `adminPassword` | random, generated once per volume | admin password of the `runServer` server (see below) |
|
||||||
|
| `serverAddress` | `127.0.0.1` | host address `runServer` publishes the game ports on; `0.0.0.0` for the network |
|
||||||
|
| `dataVolume` | `zomboidforge-<id>` | volume for the `runServer` world and server config |
|
||||||
|
| `containerEngine` | podman or docker, whichever is installed | for `runServer` and the download |
|
||||||
|
| `deployDirectory` | none | a server's mods directory for `deployMod` |
|
||||||
|
|
||||||
|
The plugin generates `META-INF/zomboidforge/mod.toml` from these settings; a hand-written one
|
||||||
|
fails the build.
|
||||||
|
|
||||||
|
Declare a minor version in `game(...)` only when the mod needs it. A mod declaring `"42.21"`
|
||||||
|
stops the server after an update to 42.22, while the server checks every game member a mod uses
|
||||||
|
against the running jar anyway.
|
||||||
|
|
||||||
|
### The game jar
|
||||||
|
|
||||||
|
Mods that declare `game` versions compile against `projectzomboid.jar`, which cannot be
|
||||||
|
published. The plugin uses the first of:
|
||||||
|
|
||||||
|
1. `zomboidForge.gameJar`, or the Gradle property `zomboidforge.gameJar` (for example in
|
||||||
|
`~/.gradle/gradle.properties`);
|
||||||
|
2. a local Steam installation of the dedicated server or the game, in any Steam library;
|
||||||
|
3. a download of the dedicated server with steamcmd (`steamcmd` if installed, otherwise its
|
||||||
|
container image with podman or docker), once per Steam branch, into the Gradle user home.
|
||||||
|
It is a few gigabytes.
|
||||||
|
|
||||||
|
The game jar has to be one of the declared `game` versions; the check below fails otherwise.
|
||||||
|
|
||||||
|
### 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)) |
|
||||||
|
| `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 |
|
||||||
|
|
||||||
|
`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
|
||||||
|
keeps it in `<Gradle user home>/zomboidforge/admin-passwords/<volume>`. The server uses the
|
||||||
|
password only when it creates the admin account, on the volume's first start; a later change
|
||||||
|
needs a new volume (`dataVolume`, or remove the old one).
|
||||||
|
|
||||||
|
### Working on ZomboidForge itself
|
||||||
|
|
||||||
|
To build a mod against a local ZomboidForge checkout instead of a published version, include it
|
||||||
|
in `settings.gradle.kts`; Gradle then builds the plugin, the API, and the mod tools from the
|
||||||
|
checkout:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
pluginManagement {
|
||||||
|
includeBuild("../ZomboidForge")
|
||||||
|
}
|
||||||
|
|
||||||
|
includeBuild("../ZomboidForge")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Entry point
|
||||||
|
|
||||||
|
The entry point extends `dev.overlord.zomboidforge.api.Mod`:
|
||||||
|
|
||||||
|
```java
|
||||||
|
public final class ShopMod extends Mod
|
||||||
|
{
|
||||||
|
record Settings(String greeting, long maxBalance) {}
|
||||||
|
|
||||||
|
private final Settings settings = this.config().bind(Settings.class); // max_balance in config.toml
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onLoad() // main thread, registration only
|
||||||
|
{
|
||||||
|
this.events().onMain(TickEvent.class, event -> { /* every frame, on the main thread */ });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onServerStarted() // world loaded, port open
|
||||||
|
{
|
||||||
|
this.modThread().scheduleAtFixedRate(() -> {
|
||||||
|
// on zf-mod-shop: slow work, no game objects
|
||||||
|
this.main().submit(GameServer::getPlayerCount) // game objects only on the main thread
|
||||||
|
.thenAcceptAsync(players -> this.logger().log(INFO, players + " online"), this.modThread());
|
||||||
|
}, Duration.ZERO, Duration.ofMinutes(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onStopping() {} // before the world is saved
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Services
|
||||||
|
|
||||||
|
Methods of `Mod`, usable from the constructor on (also in field initializers):
|
||||||
|
|
||||||
|
| Method | Returns | Use |
|
||||||
|
|-----------------|-----------------|---------------------------------------------------------------|
|
||||||
|
| `id()` | `String` | the mod's id from `mod.toml` |
|
||||||
|
| `version()` | `String` | the mod's version from `mod.toml` |
|
||||||
|
| `gameVersion()` | `GameVersion` | the running Project Zomboid version |
|
||||||
|
| `config()` | `ModConfig` | settings from `config.toml`, bound to records or read by path |
|
||||||
|
| `logger()` | `System.Logger` | messages in the Project Zomboid log, marked with the mod's id |
|
||||||
|
| `directory()` | `Path` | the mod's folder, `<forge>/mods/<id>` |
|
||||||
|
| `events()` | `Events` | event listeners |
|
||||||
|
| `main()` | `MainThread` | code that touches game objects |
|
||||||
|
| `modThread()` | `ModThread` | the mod's own work, one task at a time |
|
||||||
|
| `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O |
|
||||||
|
| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` |
|
||||||
|
|
||||||
|
## Threads
|
||||||
|
|
||||||
|
Game objects belong to the server's main thread. Everything else should stay off it, because
|
||||||
|
it also runs the game: the main loop runs about 10 frames per second.
|
||||||
|
|
||||||
|
| Executor | Thread | A task runs |
|
||||||
|
|---------------|-------------------------------------|-------------------------------------------------------------------------|
|
||||||
|
| `main()` | `main` | immediately when called on the main thread, otherwise in the next ticks |
|
||||||
|
| `modThread()` | `zf-mod-<id>` | one at a time, in the order submitted |
|
||||||
|
| `async()` | virtual threads `zf-async-<id>-<n>` | at once, each on its own thread |
|
||||||
|
|
||||||
|
Three rules follow from that:
|
||||||
|
|
||||||
|
1. Touch game objects only on the main thread; hand results over with `main().execute(...)`
|
||||||
|
or `main().submit(...)`.
|
||||||
|
2. Never wait on the main thread for another thread (`get()`, `join()`). Continue with
|
||||||
|
`thenAcceptAsync(..., modThread())` instead.
|
||||||
|
3. Keep main-thread work short. Queued tasks share a time budget per tick
|
||||||
|
(`forge.toml`, `main_thread.budget_ms`); the rest waits for the next tick.
|
||||||
|
|
||||||
|
## Events
|
||||||
|
|
||||||
|
```java
|
||||||
|
this.events().onMain(TickEvent.class, event -> ...); // main thread, while the event is posted
|
||||||
|
this.events().onModThread(SomeEvent.class, event -> ...); // later, on zf-mod-<id>
|
||||||
|
```
|
||||||
|
|
||||||
|
Listeners are matched by the event's exact class. Events that carry live game objects, such as
|
||||||
|
`TickEvent`, can only be received on the main thread. A listener that keeps throwing is
|
||||||
|
removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove
|
||||||
|
it earlier.
|
||||||
|
|
||||||
|
## Storage
|
||||||
|
|
||||||
|
Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's
|
||||||
|
save folder. Vanilla backups include it, and deleting the world deletes it. Through the API,
|
||||||
|
each mod only reaches its own tables.
|
||||||
|
|
||||||
|
A record declares a table's columns; each row has a `String` key:
|
||||||
|
|
||||||
|
```java
|
||||||
|
record Balance(long coins, @Nullable Instant lastPaid) {}
|
||||||
|
|
||||||
|
Table<Balance> balances = this.storage().table("balances", Balance.class);
|
||||||
|
|
||||||
|
balances.set("player1", new Balance(250, Instant.now()));
|
||||||
|
Optional<Balance> balance = balances.get("player1");
|
||||||
|
balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null));
|
||||||
|
|
||||||
|
this.storage().transaction(() -> { // all or nothing, also when nested
|
||||||
|
balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null));
|
||||||
|
balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null));
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
| Component type | Stored as |
|
||||||
|
|-----------------------------------|-------------------------|
|
||||||
|
| `long`, `int`, `boolean` | integer, never null |
|
||||||
|
| `double`, `float` | real number, never null |
|
||||||
|
| `Long`, `Integer`, `Boolean`, ... | the same, may be null |
|
||||||
|
| `String`, `UUID`, enums | text (enums by name) |
|
||||||
|
| `Instant` | ISO-8601 text |
|
||||||
|
| `byte[]` | blob |
|
||||||
|
|
||||||
|
Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`.
|
||||||
|
|
||||||
|
When the record changes between versions of the mod:
|
||||||
|
|
||||||
|
| Change | What happens |
|
||||||
|
|--------------------------------|-------------------------------------------|
|
||||||
|
| new component that may be null | added; existing rows read `null` |
|
||||||
|
| new primitive component | needs a migration |
|
||||||
|
| removed component | the column and its data stay; logged once |
|
||||||
|
| component with another type | needs a migration |
|
||||||
|
|
||||||
|
```java
|
||||||
|
Table<Balance> balances = this.storage().define("balances", Balance.class)
|
||||||
|
.version(2)
|
||||||
|
.migrate(1, row -> new Balance(row.getLong("coins"), null)) // from stored version 1
|
||||||
|
.open();
|
||||||
|
```
|
||||||
|
|
||||||
|
Things to know:
|
||||||
|
|
||||||
|
1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the
|
||||||
|
server runs they throw, so use `modThread()` or `async()`.
|
||||||
|
2. Writes commit immediately, while the world is saved periodically. After a crash, the
|
||||||
|
world goes back to its last save, but the mod data keeps later writes.
|
||||||
|
3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables
|
||||||
|
move to the new id once.
|
||||||
|
4. While a `transaction`, `update`, or `forEach` callback runs, the storage of every mod waits.
|
||||||
|
These callbacks must not wait for other threads, for example with
|
||||||
|
`main().submit(...).join()`. A backup waits at most 10 seconds for them and then runs
|
||||||
|
without pausing storage, so its copy of `zomboidforge.db` may be incomplete.
|
||||||
|
|
||||||
|
## Checks at startup
|
||||||
|
|
||||||
|
`checkMod` runs these checks when the mod is built, so a mod that would not load fails its
|
||||||
|
build instead. On the server, before any mod code runs, ZomboidForge reads every class of the
|
||||||
|
mod and its libraries. The server does not start when a mod
|
||||||
|
|
||||||
|
1. uses game classes without declaring `game` versions in `mod.toml`,
|
||||||
|
2. uses a game class, field, or method that does not exist in the running version,
|
||||||
|
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.
|
||||||
|
|
||||||
|
Every problem of every mod is listed in the log.
|
||||||
|
|
||||||
|
## What a mod can see
|
||||||
|
|
||||||
|
| Source | Visible |
|
||||||
|
|----------------------------------------------------|-----------------------------------------------|
|
||||||
|
| JDK | yes |
|
||||||
|
| ZomboidForge API (`dev.overlord.zomboidforge.api`) | yes |
|
||||||
|
| the mod's own jar and `lib/*.jar` | yes; own libraries win over the game's copies |
|
||||||
|
| own jars of declared dependencies | yes (not their libraries) |
|
||||||
|
| game jar (game code and its bundled libraries) | only with `game` declared |
|
||||||
|
| ZomboidForge internals | no |
|
||||||
|
|
||||||
|
These rules keep mods from linking against the wrong classes by accident. They are not a
|
||||||
|
sandbox: a mod runs with the full privileges of the server process. Through reflection or the
|
||||||
|
file system it can reach anything the server can, including other mods' data in
|
||||||
|
`zomboidforge.db`.
|
||||||
|
|
||||||
|
## Profiling
|
||||||
|
|
||||||
|
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).
|
||||||
@@ -14,16 +14,18 @@ version in `gradle.properties` (`pz.version`).
|
|||||||
podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
|
podman build --platform linux/amd64 -t zomboidforge . # or: docker build ...
|
||||||
```
|
```
|
||||||
|
|
||||||
| Build argument | Default | |
|
| Build argument | Default | |
|
||||||
|---|---|---|
|
|--------------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||||
| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` |
|
| `PZ_BRANCH` | `public` | Steam branch: `public`, `unstable`, or a version branch such as `42.19` |
|
||||||
| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version |
|
| `PZ_VERSION` | `pz.version` | Expected Project Zomboid version |
|
||||||
| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) |
|
| `STEAMCLIENT` | `bundled` | `steamcmd` replaces the server's `steamclient.so` files with steamcmd's newer copies (workaround for failing Workshop downloads) |
|
||||||
| `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it |
|
| `FORGE_VERSION` | `0.0.0-prerelease` | ZomboidForge version (jar manifest, image label). The build stage has no `git`, so the version is never read from a tag there; `ci/release.sh` passes it |
|
||||||
| `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` |
|
| `DISABLED_PATCHES` | | Comma-separated simple class names of build-time patches to skip (debug builds only), e.g. `IsoZombieVehiclePerformancePatch` |
|
||||||
|
|
||||||
Published images are tagged `<forge>-pz<pz>-build<steam buildid>` (immutable),
|
Published images are tagged `<forge>-pz<major.minor.build>` (never overwritten),
|
||||||
`<forge>-pz<pz>`, and `latest`.
|
`<forge>-pz<major.minor>` (the newest hotfix of that minor version), and `latest`. A new image
|
||||||
|
is built for every ZomboidForge release and every Project Zomboid version, hotfixes included:
|
||||||
|
the server only admits clients with the same version.
|
||||||
|
|
||||||
## Running
|
## Running
|
||||||
|
|
||||||
@@ -36,24 +38,24 @@ podman run -d --name zomboidforge \
|
|||||||
|
|
||||||
Unset variables keep the value in the server `.ini` (or the game default).
|
Unset variables keep the value in the server `.ini` (or the game default).
|
||||||
|
|
||||||
| Variable | Default | |
|
| Variable | Default | |
|
||||||
|---|---|---|
|
|-------------------|----------------|-----------------------------------------------------------------------------------------------------|
|
||||||
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
|
| `SERVER_NAME` | `zomboidforge` | Server config name (`/data/Server/<name>.ini`) |
|
||||||
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
|
| `SERVER_PASSWORD` | | Password clients need to join (`.ini` `Password`) |
|
||||||
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
|
| `PUBLIC` | | `true`/`false`: listed in the in-game server browser |
|
||||||
| `PUBLIC_NAME` | | Name in the server browser |
|
| `PUBLIC_NAME` | | Name in the server browser |
|
||||||
| `PORT` | `16261` | Game port (`-port`) |
|
| `PORT` | `16261` | Game port (`-port`) |
|
||||||
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
|
| `UDP_PORT` | `16262` | Direct connection port (`-udpport`) |
|
||||||
| `ADMIN_USERNAME` | `admin` | First start only |
|
| `ADMIN_USERNAME` | `admin` | First start only |
|
||||||
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
|
| `ADMIN_PASSWORD` | | Required on the first start, ignored afterwards |
|
||||||
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
|
| `SERVER_PRESET` | | Sandbox preset for a new server: `Apocalypse`, `Extinction`, `Outbreak`, `Rising`, `SixMonthsLater` |
|
||||||
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
|
| `MODS` | | Mod IDs, Build 42 format: `\ModA;\ModB` |
|
||||||
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
|
| `WORKSHOP_ITEMS` | | Workshop item IDs: `123;456` |
|
||||||
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
|
| `RCON_PASSWORD` | | Written into the `.ini` on every start; RCON is disabled without it |
|
||||||
| `JVM_MIN_HEAP` | | `-Xms` |
|
| `JVM_MIN_HEAP` | `JVM_MAX_HEAP` | `-Xms` |
|
||||||
| `JVM_MAX_HEAP` | `8g` | `-Xmx` |
|
| `JVM_MAX_HEAP` | `8g` | `-Xmx` |
|
||||||
| `STEAM` | `1` | `0` runs the server without Steam |
|
| `STEAM` | `1` | `0` runs the server without Steam |
|
||||||
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
|
| `SOFT_RESET` | | `true` starts once in soft reset mode (`-Dsoftreset`); unset it afterwards |
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
@@ -69,6 +71,64 @@ Notes:
|
|||||||
|
|
||||||
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`).
|
For local testing there is `compose.yaml` (`podman compose up --build`, settings from `.env`).
|
||||||
|
|
||||||
|
## Mods
|
||||||
|
|
||||||
|
ZomboidForge loads server-side Java mods. They run only on the server, so players keep the
|
||||||
|
official, unmodified client. Project Zomboid's own Lua and Workshop mods are configured as
|
||||||
|
usual with `MODS` and `WORKSHOP_ITEMS`.
|
||||||
|
|
||||||
|
### Installing mods
|
||||||
|
|
||||||
|
Mount a directory at `/forge` with one folder per mod:
|
||||||
|
|
||||||
|
```
|
||||||
|
forge/
|
||||||
|
├── forge.toml optional global settings
|
||||||
|
└── mods/
|
||||||
|
└── <id>/
|
||||||
|
├── <id>.jar the mod
|
||||||
|
├── lib/*.jar libraries of the mod (optional)
|
||||||
|
└── config.toml settings of the mod (optional)
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
podman run ... -v ./forge:/forge zomboidforge
|
||||||
|
```
|
||||||
|
|
||||||
|
Mods are trusted code. They run inside the server process with its full privileges: they can
|
||||||
|
read and write any file the server can, open network connections, and stop the server. The
|
||||||
|
class loader isolation and the startup checks catch mistakes; they do not contain a malicious
|
||||||
|
mod. Install only mods whose authors you trust.
|
||||||
|
|
||||||
|
A mod's settings live in its `config.toml`. When the file is missing, it is created from the
|
||||||
|
mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a
|
||||||
|
file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]`
|
||||||
|
table switches the mod off; mods that depend on it then fail to load.
|
||||||
|
|
||||||
|
Mods keep their data in `zomboidforge.db` in the world's save folder
|
||||||
|
(`/data/Saves/Multiplayer/<server>/`). Vanilla backups include it, and deleting the world
|
||||||
|
deletes it.
|
||||||
|
|
||||||
|
A mod that cannot be loaded stops the server with exit code 1, and the log lists every
|
||||||
|
problem: a missing or too old dependency, an unsupported game version, game classes or methods
|
||||||
|
that do not exist in the running version, invalid settings, or an exception in the mod's
|
||||||
|
startup code. Changes to mods and their settings take effect when the server restarts.
|
||||||
|
|
||||||
|
`forge.toml`, every key optional:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[main_thread]
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mod development
|
||||||
|
|
||||||
|
Writing a mod (descriptor, entry point, threads, events, settings, startup checks):
|
||||||
|
[MOD_DEVELOPMENT.md](MOD_DEVELOPMENT.md).
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
Requires JDK 25 (the game's runtime). The Gradle build compiles against a local vanilla
|
Requires JDK 25 (the game's runtime). The Gradle build compiles against a local vanilla
|
||||||
@@ -80,4 +140,8 @@ server jar, `lib/server/java/projectzomboid.jar` by default (override with `-Ppz
|
|||||||
```
|
```
|
||||||
|
|
||||||
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
|
Game-specific code lives in `compat/b<major>/`; `api` and `core` are version-independent.
|
||||||
`pz.version` in `gradle.properties` selects the targeted version.
|
`pz.version` in `gradle.properties` selects the targeted version. `mod-tools` (the build-time
|
||||||
|
mod checks) and `gradle-plugin` (the plugin for mod authors) are for mod builds, not the server.
|
||||||
|
|
||||||
|
Release tags publish `api`, `mod-tools`, and the Gradle plugin to the Gitea Maven registry
|
||||||
|
(`.gitea/workflows/publish.yml`, `ci/publish.sh`); tags with a `-` are only tested.
|
||||||
+15
-5
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id("zomboidforge.java-conventions")
|
id("zomboidforge.java-conventions")
|
||||||
|
alias(libs.plugins.shadow)
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
@@ -11,10 +12,19 @@ dependencies {
|
|||||||
compileOnly(files(projectZomboid.serverJar))
|
compileOnly(files(projectZomboid.serverJar))
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.jar {
|
// The agent jar is appended to the system class path behind the game jar and includes api,
|
||||||
archiveBaseName = "zomboidforge-agent"
|
// core, compat runtime, and their libraries. The libraries are relocated, so a copy of the same
|
||||||
|
// library in the game jar cannot replace them.
|
||||||
|
tasks.shadowJar {
|
||||||
|
archiveBaseName = "zomboidforge-agent"
|
||||||
|
archiveClassifier = ""
|
||||||
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
|
manifest.attributes("Premain-Class" to "dev.overlord.zomboidforge.agent.ForgeAgent")
|
||||||
// The agent jar is appended to the system class path and includes api, core and compat runtime.
|
|
||||||
from(configurations.runtimeClasspath.map { classpath -> classpath.map { zipTree(it) } })
|
relocate("org.objectweb.asm", "dev.overlord.zomboidforge.shaded.asm")
|
||||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
relocate("com.electronwill.nightconfig", "dev.overlord.zomboidforge.shaded.nightconfig")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only the shadow jar is used; the plain jar would match the same file name pattern.
|
||||||
|
tasks.jar {
|
||||||
|
enabled = false
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,38 @@
|
|||||||
// API for custom Java mods. Version-independent: no references to game classes.
|
// API for custom Java mods. Version-independent: no references to game classes.
|
||||||
|
// Published as dev.overlord.zomboidforge:api; mods compile against it.
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id("zomboidforge.java-conventions")
|
id("zomboidforge.java-conventions")
|
||||||
|
id("zomboidforge.publishing")
|
||||||
|
`java-library`
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
withSourcesJar()
|
||||||
|
withJavadocJar()
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.javadoc {
|
||||||
|
// api.internal connects the API to the runtime and is not part of the documented API.
|
||||||
|
exclude("dev/overlord/zomboidforge/api/internal/**")
|
||||||
|
|
||||||
|
(options as StandardJavadocDocletOptions).apply {
|
||||||
|
// IntelliJ's @noinspection in package-info.java is not a Javadoc tag.
|
||||||
|
tags("noinspection:X")
|
||||||
|
addStringOption("Xdoclint:all,-missing", "-quiet")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
publications {
|
||||||
|
create<MavenPublication>("api") {
|
||||||
|
from(components["java"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
testImplementation(platform(libs.junit.bom))
|
||||||
|
testImplementation(libs.junit.jupiter)
|
||||||
|
testRuntimeOnly(libs.junit.platform.launcher)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Virtual threads for a mod's blocking work, such as HTTP calls or file I/O: one thread per
|
||||||
|
* task, named {@code zf-async-<id>-<n>}. ZomboidForge shuts it down when the server stops; tasks
|
||||||
|
* submitted after that are rejected with a {@link java.util.concurrent.RejectedExecutionException}.
|
||||||
|
*/
|
||||||
|
public interface AsyncExecutor extends Executor
|
||||||
|
{
|
||||||
|
/** Runs {@code task} on a new virtual thread. An exception it throws is logged with the mod's id. */
|
||||||
|
@Override
|
||||||
|
void execute(Runnable task);
|
||||||
|
|
||||||
|
/** Runs {@code task} on a new virtual thread; the future completes with its result or exception. */
|
||||||
|
<T> CompletableFuture<T> submit(Callable<T> task);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Something that happened in the server, delivered to listeners registered with
|
||||||
|
* {@link Events}. Listeners are matched by the event's exact class.
|
||||||
|
*/
|
||||||
|
public interface Event {}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registration of event listeners. Listeners of one event run in registration order. A listener
|
||||||
|
* that throws is logged with the mod's id; one that throws repeatedly is removed.
|
||||||
|
*/
|
||||||
|
public interface Events
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* {@code listener} runs on the main thread while the event is posted. It may touch game
|
||||||
|
* objects and must return quickly: it runs inside the tick.
|
||||||
|
*/
|
||||||
|
<E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code listener} runs later on the mod's own thread. It must not touch game objects;
|
||||||
|
* main-thread work goes through {@code main()}.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException when {@code type} is a {@link MainThreadEvent}
|
||||||
|
*/
|
||||||
|
<E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener);
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/** Project Zomboid version, e.g. 42.21.0 ({@code Core.getGameAndBuildVersion()}). */
|
||||||
|
public record GameVersion(int major, int minor, int build) implements Comparable<GameVersion>
|
||||||
|
{
|
||||||
|
// At most 9 digits per number, so every number fits an int.
|
||||||
|
private static final Pattern VERSION = Pattern.compile("(\\d{1,9})\\.(\\d{1,9})(?:\\.(\\d{1,9}))?");
|
||||||
|
private static final Pattern PREFIX = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9})(?:\\.(\\d{1,9}))?)?");
|
||||||
|
|
||||||
|
private static final Comparator<GameVersion> ORDER = Comparator
|
||||||
|
.comparingInt(GameVersion::major)
|
||||||
|
.thenComparingInt(GameVersion::minor)
|
||||||
|
.thenComparingInt(GameVersion::build);
|
||||||
|
|
||||||
|
/** Parses "42.21.0", or "42.21" as 42.21.0. */
|
||||||
|
public static GameVersion parse(String text)
|
||||||
|
{
|
||||||
|
Matcher matcher = GameVersion.VERSION.matcher(text.trim());
|
||||||
|
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version: '" + text + "'.");
|
||||||
|
|
||||||
|
int build = matcher.group(3) == null
|
||||||
|
? 0
|
||||||
|
: Integer.parseInt(matcher.group(3));
|
||||||
|
|
||||||
|
return new GameVersion(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), build);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether {@code text} is a version prefix for {@link #matches}: "42", "42.21", or "42.21.0". */
|
||||||
|
public static boolean isPrefix(String text) { return GameVersion.PREFIX.matcher(text.trim()).matches(); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this version starts with {@code prefix}: "42" matches every 42.x.y, "42.21" every
|
||||||
|
* 42.21.x, "42.21.0" only 42.21.0.
|
||||||
|
*/
|
||||||
|
public boolean matches(String prefix)
|
||||||
|
{
|
||||||
|
Matcher matcher = GameVersion.PREFIX.matcher(prefix.trim());
|
||||||
|
if (!matcher.matches()) throw new IllegalArgumentException("Not a Project Zomboid version prefix: '" + prefix + "'.");
|
||||||
|
|
||||||
|
return GameVersion.partMatches(matcher.group(1), this.major)
|
||||||
|
&& GameVersion.partMatches(matcher.group(2), this.minor)
|
||||||
|
&& GameVersion.partMatches(matcher.group(3), this.build);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isAtLeast(int major, int minor) { return this.compareTo(new GameVersion(major, minor, 0)) >= 0; }
|
||||||
|
|
||||||
|
public boolean isBefore(int major, int minor) { return this.compareTo(new GameVersion(major, minor, 0)) < 0; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(GameVersion other) { return GameVersion.ORDER.compare(this, other); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() { return this.major + "." + this.minor + "." + this.build; }
|
||||||
|
|
||||||
|
/** A missing part of a prefix matches any value. */
|
||||||
|
private static boolean partMatches(@Nullable String part, int value) { return part == null || Integer.parseInt(part) == value; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs a mod's code on the server's main thread, which owns every game object. Tasks from other
|
||||||
|
* threads are queued and run during the next ticks, within a time budget per tick
|
||||||
|
* ({@code forge.toml}); a task is never interrupted. Called on the main thread itself,
|
||||||
|
* {@link #execute} and {@link #submit} run the task immediately.
|
||||||
|
*
|
||||||
|
* <p>Callbacks of the returned futures run on the thread that completes them, which is the
|
||||||
|
* main thread: {@code submit(...).thenAcceptAsync(result -> ..., modThread())} moves the
|
||||||
|
* follow-up work back. The main thread must never wait for another thread's result.
|
||||||
|
*/
|
||||||
|
public interface MainThread extends Executor
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Runs {@code task} on the main thread. An exception it throws is logged with the mod's id.
|
||||||
|
*
|
||||||
|
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
void execute(Runnable task);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs {@code task} on the main thread; the future completes with its result or exception.
|
||||||
|
*
|
||||||
|
* @throws java.util.concurrent.RejectedExecutionException after the server started stopping
|
||||||
|
*/
|
||||||
|
<T> CompletableFuture<T> submit(Callable<T> task);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queues {@code task} to run on the main thread {@code ticks} frames from now, also when
|
||||||
|
* called on the main thread.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException when {@code ticks} is less than 1
|
||||||
|
*/
|
||||||
|
void runLater(int ticks, Runnable task);
|
||||||
|
|
||||||
|
/** Whether the calling thread is the main thread. */
|
||||||
|
boolean isMainThread();
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An event that carries live game state or only makes sense during the tick. Listeners for it
|
||||||
|
* run on the main thread only; {@link Events#onModThread} rejects it.
|
||||||
|
*/
|
||||||
|
public interface MainThreadEvent extends Event {}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.internal.ModBinding;
|
||||||
|
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class of every mod. The class named as {@code entrypoint} in {@code mod.toml} extends it
|
||||||
|
* and has a public constructor without parameters.
|
||||||
|
*
|
||||||
|
* <p>ZomboidForge creates one instance per mod on the main thread, in dependency order, while
|
||||||
|
* the server starts. The methods of this class work from the constructor on, so field
|
||||||
|
* initializers may use them.
|
||||||
|
*
|
||||||
|
* <p>Lifecycle, in this order:
|
||||||
|
* <ol>
|
||||||
|
* <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 #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.
|
||||||
|
*/
|
||||||
|
public abstract class Mod
|
||||||
|
{
|
||||||
|
private final ModContext context;
|
||||||
|
|
||||||
|
/** @throws IllegalStateException when the instance is not created by ZomboidForge */
|
||||||
|
protected Mod()
|
||||||
|
{
|
||||||
|
if (!ModBinding.CONTEXT.isBound())
|
||||||
|
throw new IllegalStateException("'" + this.getClass().getName() + "' can only be created by ZomboidForge.");
|
||||||
|
|
||||||
|
this.context = ModBinding.CONTEXT.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The id from {@code mod.toml}. */
|
||||||
|
public final String id() { return this.context.id(); }
|
||||||
|
|
||||||
|
/** The version from {@code mod.toml}. */
|
||||||
|
public final String version() { return this.context.version(); }
|
||||||
|
|
||||||
|
/** Called once on the main thread, after the instance is created. */
|
||||||
|
@SuppressWarnings("RedundantThrows")
|
||||||
|
public void onLoad() throws Exception {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
*/
|
||||||
|
public void onStopping() {}
|
||||||
|
|
||||||
|
/** The running Project Zomboid version. */
|
||||||
|
protected final GameVersion gameVersion() { return this.context.gameVersion(); }
|
||||||
|
|
||||||
|
/** Logger whose messages go into the Project Zomboid log, marked with the mod's id. */
|
||||||
|
protected final System.Logger logger() { return this.context.logger(); }
|
||||||
|
|
||||||
|
/** The mod's folder, {@code <forge>/mods/<id>}. */
|
||||||
|
protected final Path directory() { return this.context.directory(); }
|
||||||
|
|
||||||
|
/** The mod's settings from {@code config.toml}. */
|
||||||
|
protected final ModConfig config() { return this.context.config(); }
|
||||||
|
|
||||||
|
/** Event listener registration. */
|
||||||
|
protected final Events events() { return this.context.events(); }
|
||||||
|
|
||||||
|
/** The server's main thread, for everything that touches game objects. */
|
||||||
|
@SuppressWarnings("ConfusingMainMethod")
|
||||||
|
protected final MainThread main() { return this.context.main(); }
|
||||||
|
|
||||||
|
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
|
||||||
|
protected final ModThread modThread() { return this.context.modThread(); }
|
||||||
|
|
||||||
|
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
|
||||||
|
protected final AsyncExecutor async() { return this.context.async(); }
|
||||||
|
|
||||||
|
/** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */
|
||||||
|
protected final ModStorage storage() { return this.context.storage(); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings of one mod: {@code <forge>/mods/<id>/config.toml}, over the defaults in the mod's
|
||||||
|
* jar ({@code META-INF/zomboidforge/config.toml}). A key missing from the file takes the
|
||||||
|
* 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}).
|
||||||
|
*/
|
||||||
|
public interface ModConfig
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Creates a record from the settings. Supported component types: {@code String},
|
||||||
|
* {@code boolean}, {@code int}, {@code long}, {@code float}, {@code double} (and their
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* @throws IllegalStateException listing every missing or mistyped value
|
||||||
|
*/
|
||||||
|
<T extends Record> T bind(Class<T> type);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The value at a dotted path, e.g. {@code "features.max_balance"}, converted like a record
|
||||||
|
* component of {@code type}. Primitive values use the wrapper types ({@code Long.class}).
|
||||||
|
*
|
||||||
|
* @throws IllegalStateException when the value exists but has another type
|
||||||
|
*/
|
||||||
|
<T> Optional<T> get(String path, Class<T> type);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What ZomboidForge provides to one mod. Mods reach it through the methods of {@link Mod};
|
||||||
|
* ZomboidForge implements it.
|
||||||
|
*/
|
||||||
|
public interface ModContext
|
||||||
|
{
|
||||||
|
/** The mod's id from {@code mod.toml}. */
|
||||||
|
String id();
|
||||||
|
|
||||||
|
/** The mod's version from {@code mod.toml}. */
|
||||||
|
String version();
|
||||||
|
|
||||||
|
/** The running Project Zomboid version. */
|
||||||
|
GameVersion gameVersion();
|
||||||
|
|
||||||
|
/** Logger whose messages go into the Project Zomboid log, marked with the mod's id. */
|
||||||
|
System.Logger logger();
|
||||||
|
|
||||||
|
/** The mod's folder, {@code <forge>/mods/<id>}. */
|
||||||
|
Path directory();
|
||||||
|
|
||||||
|
/** The mod's settings from {@code config.toml}. */
|
||||||
|
ModConfig config();
|
||||||
|
|
||||||
|
/** Event listener registration. */
|
||||||
|
Events events();
|
||||||
|
|
||||||
|
/** The server's main thread, for everything that touches game objects. */
|
||||||
|
MainThread main();
|
||||||
|
|
||||||
|
/** The mod's own platform thread, {@code zf-mod-<id>}: one task at a time, in order. */
|
||||||
|
ModThread modThread();
|
||||||
|
|
||||||
|
/** Virtual threads for blocking work such as HTTP calls or file I/O. */
|
||||||
|
AsyncExecutor async();
|
||||||
|
|
||||||
|
/** The mod's tables in the world's {@code zomboidforge.db}. */
|
||||||
|
ModStorage storage();
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mod's own platform thread, {@code zf-mod-<id>}: runs one task at a time, in the order
|
||||||
|
* they were submitted. ZomboidForge shuts it down when the server stops; tasks submitted after
|
||||||
|
* that are rejected with a {@link java.util.concurrent.RejectedExecutionException}. It must not
|
||||||
|
* touch game objects; that goes through {@code main()}.
|
||||||
|
*/
|
||||||
|
public interface ModThread extends Executor
|
||||||
|
{
|
||||||
|
/** Runs {@code task} on the mod thread. An exception it throws is logged with the mod's id. */
|
||||||
|
@Override
|
||||||
|
void execute(Runnable task);
|
||||||
|
|
||||||
|
/** Runs {@code task} on the mod thread; the future completes with its result or exception. */
|
||||||
|
<T> CompletableFuture<T> submit(Callable<T> task);
|
||||||
|
|
||||||
|
/** Runs {@code task} once after {@code delay}. An exception it throws is logged. */
|
||||||
|
ScheduledFuture<?> schedule(Runnable task, Duration delay);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs {@code task} after {@code initialDelay}, then every {@code period}, measured from the
|
||||||
|
* start of each run. A run that throws is logged and ends the schedule.
|
||||||
|
*/
|
||||||
|
ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration initialDelay, Duration period);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs {@code task} after {@code initialDelay}, then again {@code delay} after each run
|
||||||
|
* finished. A run that throws is logged and ends the schedule.
|
||||||
|
*/
|
||||||
|
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration initialDelay, Duration delay);
|
||||||
|
|
||||||
|
/** Whether the calling thread is this mod thread. */
|
||||||
|
boolean isModThread();
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
/** A registered event listener. */
|
||||||
|
public interface Subscription
|
||||||
|
{
|
||||||
|
/** Removes the listener; it receives no further events. Calling it again has no effect. */
|
||||||
|
void cancel();
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Posted on the main thread once per frame of the main loop, before the queued main-thread
|
||||||
|
* tasks run.
|
||||||
|
*
|
||||||
|
* @param tick number of the frame, counted from 1 at the first frame after the server started
|
||||||
|
*/
|
||||||
|
public record TickEvent(long tick) implements MainThreadEvent {}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package dev.overlord.zomboidforge.api.internal;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.ModContext;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.ApiStatus.Internal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The context of the mod being created. ZomboidForge binds it while it calls a mod's
|
||||||
|
* constructor; the {@code Mod} constructor reads it.
|
||||||
|
*/
|
||||||
|
@Internal
|
||||||
|
public final class ModBinding
|
||||||
|
{
|
||||||
|
public static final ScopedValue<ModContext> CONTEXT = ScopedValue.newInstance();
|
||||||
|
|
||||||
|
private ModBinding() {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* Connection between the API and the ZomboidForge runtime. Not part of the mod API.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.api.internal;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package dev.overlord.zomboidforge.api.storage;
|
||||||
|
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The mod's tables in {@code zomboidforge.db}, next to the world's save. Every table belongs to
|
||||||
|
* the mod; this interface gives no access to the tables of other mods. It is not a security
|
||||||
|
* boundary: mod code runs with the server's privileges and can open the file directly.
|
||||||
|
*
|
||||||
|
* <p>A record declares a table's columns: {@code String}, {@code long}/{@code int},
|
||||||
|
* {@code double}/{@code float}, {@code boolean}, {@code byte[]}, {@code UUID}, {@code Instant},
|
||||||
|
* and enums. Primitive components cannot be null. Table and column names are {@code snake_case}
|
||||||
|
* ({@code lastPaid} is stored as {@code last_paid}).
|
||||||
|
*
|
||||||
|
* <p>Calls block. On the main thread they are only allowed during startup ({@code onLoad});
|
||||||
|
* once the server runs they throw an {@link IllegalStateException}, so database I/O never costs
|
||||||
|
* tick time. Use {@code modThread()} or {@code async()}.
|
||||||
|
*/
|
||||||
|
public interface ModStorage
|
||||||
|
{
|
||||||
|
/** Opens the table {@code name} with schema version 1 and no migrations. */
|
||||||
|
<R extends Record> Table<R> table(String name, Class<R> type);
|
||||||
|
|
||||||
|
/** A table with a schema version and migrations; see {@link TableDefinition}. */
|
||||||
|
<R extends Record> TableDefinition<R> define(String name, Class<R> type);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs {@code work} in one transaction: writes of this thread inside it are committed
|
||||||
|
* together, or not at all when {@code work} throws.
|
||||||
|
*
|
||||||
|
* <p>Storage of every mod waits while {@code work} runs, so {@code work} must not wait for
|
||||||
|
* other threads, for example with {@code main().submit(...).join()}. A backup waits at most
|
||||||
|
* 10 seconds for it and then runs without pausing storage.
|
||||||
|
*/
|
||||||
|
void transaction(Runnable work);
|
||||||
|
|
||||||
|
/** Like {@link #transaction(Runnable)}, returning the result of {@code work}. */
|
||||||
|
<T> T transaction(Supplier<T> work);
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package dev.overlord.zomboidforge.api.storage;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One row of a table in its stored form, given to migrations: the key and the columns by
|
||||||
|
* their {@code snake_case} names. Integers and booleans are stored as {@code Long}, other
|
||||||
|
* numbers as {@code Double}, texts (also UUIDs, instants, and enum constants) as
|
||||||
|
* {@code String}, bytes as {@code byte[]}.
|
||||||
|
*/
|
||||||
|
public interface Row
|
||||||
|
{
|
||||||
|
String key();
|
||||||
|
|
||||||
|
/** The names of the stored columns. */
|
||||||
|
Set<String> columns();
|
||||||
|
|
||||||
|
/** The stored value, or {@code null} when it is null. @throws IllegalArgumentException for an unknown column */
|
||||||
|
@Nullable Object get(String column);
|
||||||
|
|
||||||
|
@Nullable String getString(String column);
|
||||||
|
|
||||||
|
/** @throws IllegalStateException when the value is null */
|
||||||
|
long getLong(String column);
|
||||||
|
|
||||||
|
/** @throws IllegalStateException when the value is null */
|
||||||
|
double getDouble(String column);
|
||||||
|
|
||||||
|
/** @throws IllegalStateException when the value is null */
|
||||||
|
boolean getBoolean(String column);
|
||||||
|
|
||||||
|
byte @Nullable [] getBytes(String column);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package dev.overlord.zomboidforge.api.storage;
|
||||||
|
|
||||||
|
import java.io.Serial;
|
||||||
|
|
||||||
|
/** A storage operation failed: a database error, or a table that does not match its record. */
|
||||||
|
public final class StorageException extends RuntimeException
|
||||||
|
{
|
||||||
|
@Serial
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
public StorageException(String message) { super(message); }
|
||||||
|
|
||||||
|
public StorageException(String message, Throwable cause) { super(message, cause); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package dev.overlord.zomboidforge.api.storage;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.function.UnaryOperator;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rows of type {@code R}, each under a {@code String} key. Every write commits immediately,
|
||||||
|
* unless it runs inside {@link ModStorage#transaction}. Calls block; on the main thread they
|
||||||
|
* are only allowed during startup.
|
||||||
|
*/
|
||||||
|
public interface Table<R extends Record>
|
||||||
|
{
|
||||||
|
/** Stores {@code value} under {@code key}, replacing an existing row. */
|
||||||
|
void set(String key, R value);
|
||||||
|
|
||||||
|
/** Stores every entry in one transaction. */
|
||||||
|
void setAll(Map<String, R> values);
|
||||||
|
|
||||||
|
Optional<R> get(String key);
|
||||||
|
|
||||||
|
/** The rows of the given keys that exist. */
|
||||||
|
Map<String, R> getAll(Collection<String> keys);
|
||||||
|
|
||||||
|
boolean contains(String key);
|
||||||
|
|
||||||
|
/** @return whether a row was removed */
|
||||||
|
boolean delete(String key);
|
||||||
|
|
||||||
|
/** @return the number of rows removed */
|
||||||
|
int deleteAll(Collection<String> keys);
|
||||||
|
|
||||||
|
/** Every key, sorted. */
|
||||||
|
List<String> keys();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls {@code action} for every row, sorted by key, without loading all rows at once.
|
||||||
|
* Storage of every mod waits until it returns, so {@code action} must not wait for other
|
||||||
|
* threads.
|
||||||
|
*/
|
||||||
|
void forEach(BiConsumer<String, R> action);
|
||||||
|
|
||||||
|
long count();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the row under {@code key} with {@code change} applied to it, or to
|
||||||
|
* {@code initial} when there is none, in one transaction: no other write comes in between.
|
||||||
|
* As in {@link ModStorage#transaction}, {@code change} and {@code initial} must not wait for
|
||||||
|
* other threads.
|
||||||
|
*
|
||||||
|
* @return the stored value
|
||||||
|
*/
|
||||||
|
R update(String key, UnaryOperator<R> change, Supplier<R> initial);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package dev.overlord.zomboidforge.api.storage;
|
||||||
|
|
||||||
|
import java.util.function.Function;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A table to open with a schema version and migrations:
|
||||||
|
*
|
||||||
|
* <pre>{@code
|
||||||
|
* Table<Balance> balances = this.storage().define("balances", Balance.class)
|
||||||
|
* .version(2)
|
||||||
|
* .migrate(1, row -> new Balance(row.getLong("coins"), null))
|
||||||
|
* .open();
|
||||||
|
* }</pre>
|
||||||
|
*/
|
||||||
|
public interface TableDefinition<R extends Record>
|
||||||
|
{
|
||||||
|
/** Schema version of the record, at least 1. Default: 1. */
|
||||||
|
TableDefinition<R> version(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.
|
||||||
|
*/
|
||||||
|
TableDefinition<R> migrate(int from, Function<Row, R> migration);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates the table, or checks the stored one against the record and migrates it.
|
||||||
|
*
|
||||||
|
* @throws StorageException when the stored table does not match and no migration applies
|
||||||
|
*/
|
||||||
|
Table<R> open();
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* Per-world storage for mods: record tables in a SQLite database next to the save, kept
|
||||||
|
* apart by mod id.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.api.storage;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
+35
-6
@@ -1,4 +1,4 @@
|
|||||||
package dev.overlord.zomboidforge.patcher;
|
package dev.overlord.zomboidforge.api;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@@ -7,9 +7,11 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
class GameVersionTest {
|
class GameVersionTest
|
||||||
|
{
|
||||||
@Test
|
@Test
|
||||||
void parsesTwoAndThreePartVersions() {
|
void parsesTwoAndThreePartVersions()
|
||||||
|
{
|
||||||
assertEquals(new GameVersion(42, 21, 0), GameVersion.parse("42.21"));
|
assertEquals(new GameVersion(42, 21, 0), GameVersion.parse("42.21"));
|
||||||
assertEquals(new GameVersion(42, 21, 3), GameVersion.parse("42.21.3"));
|
assertEquals(new GameVersion(42, 21, 3), GameVersion.parse("42.21.3"));
|
||||||
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42"));
|
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42"));
|
||||||
@@ -17,17 +19,44 @@ class GameVersionTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void twoPartExpectationMatchesEveryBuild() {
|
void prefixMatchesEveryMissingPart()
|
||||||
|
{
|
||||||
GameVersion version = new GameVersion(42, 21, 3);
|
GameVersion version = new GameVersion(42, 21, 3);
|
||||||
|
|
||||||
|
assertTrue(version.matches("42"));
|
||||||
assertTrue(version.matches("42.21"));
|
assertTrue(version.matches("42.21"));
|
||||||
assertTrue(version.matches("42.21.3"));
|
assertTrue(version.matches("42.21.3"));
|
||||||
assertFalse(version.matches("42.21.0"));
|
assertFalse(version.matches("41"));
|
||||||
assertFalse(version.matches("42.20"));
|
assertFalse(version.matches("42.20"));
|
||||||
|
assertFalse(version.matches("42.21.0"));
|
||||||
|
assertFalse(version.matches("4"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void comparesNumerically() {
|
void rejectsMalformedPrefixes()
|
||||||
|
{
|
||||||
|
GameVersion version = new GameVersion(42, 21, 3);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> version.matches(""));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> version.matches("42."));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> version.matches("42.21.3.1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsNumbersOutsideTheIntRange()
|
||||||
|
{
|
||||||
|
GameVersion version = new GameVersion(42, 21, 3);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> GameVersion.parse("42.99999999999"));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> version.matches("99999999999"));
|
||||||
|
assertFalse(GameVersion.isPrefix("42.99999999999"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void comparesNumerically()
|
||||||
|
{
|
||||||
GameVersion version = new GameVersion(42, 21, 0);
|
GameVersion version = new GameVersion(42, 21, 0);
|
||||||
|
|
||||||
assertTrue(version.isAtLeast(42, 9));
|
assertTrue(version.isAtLeast(42, 9));
|
||||||
assertTrue(version.isAtLeast(42, 21));
|
assertTrue(version.isAtLeast(42, 21));
|
||||||
assertFalse(version.isAtLeast(42, 22));
|
assertFalse(version.isAtLeast(42, 22));
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Publishing to the Maven registry of the ZomboidForge Gitea. Credentials come from the Gradle
|
||||||
|
// properties giteaUsername and giteaPassword (or ORG_GRADLE_PROJECT_giteaUsername and
|
||||||
|
// ORG_GRADLE_PROJECT_giteaPassword), and are only read when a publish task runs.
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
`maven-publish`
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
repositories {
|
||||||
|
maven {
|
||||||
|
name = "gitea"
|
||||||
|
url = uri("https://git.security-command.org/api/packages/overlord/maven")
|
||||||
|
credentials(PasswordCredentials::class)
|
||||||
|
}
|
||||||
|
|
||||||
|
// build/repo of the root project: for the Gradle plugin's functional tests.
|
||||||
|
maven {
|
||||||
|
name = "build"
|
||||||
|
url = uri(layout.settingsDirectory.dir("build/repo"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+115
@@ -0,0 +1,115 @@
|
|||||||
|
#!/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".
|
||||||
|
#
|
||||||
|
# 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.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# ci/publish.sh test runs the checks of the published modules; needs no credentials
|
||||||
|
# ci/publish.sh publish publishes them without running the checks again
|
||||||
|
#
|
||||||
|
# Environment (publish only):
|
||||||
|
# ORG_GRADLE_PROJECT_giteaUsername Gitea user with package write access
|
||||||
|
# ORG_GRADLE_PROJECT_giteaPassword Token of that user
|
||||||
|
|
||||||
|
set -o errexit
|
||||||
|
set -o nounset
|
||||||
|
set -o pipefail
|
||||||
|
|
||||||
|
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
readonly REPO_ROOT
|
||||||
|
|
||||||
|
readonly MODULES=(
|
||||||
|
api
|
||||||
|
mod-tools
|
||||||
|
gradle-plugin
|
||||||
|
)
|
||||||
|
|
||||||
|
log() {
|
||||||
|
echo "[publish] $*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prints the v* tag on HEAD without its "v", or nothing.
|
||||||
|
release_tag_version() {
|
||||||
|
local tag
|
||||||
|
|
||||||
|
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||||
|
echo "${tag#v}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gradle tasks for every module, e.g. ":api:check".
|
||||||
|
module_tasks() {
|
||||||
|
local task="$1"
|
||||||
|
local module
|
||||||
|
|
||||||
|
for module in "${MODULES[@]}"; do
|
||||||
|
echo ":${module}:${task}"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
run_gradle() {
|
||||||
|
local version="$1"
|
||||||
|
shift
|
||||||
|
|
||||||
|
"${REPO_ROOT}/gradlew" \
|
||||||
|
--no-daemon \
|
||||||
|
--project-dir "${REPO_ROOT}" \
|
||||||
|
"-Pversion=${version}" \
|
||||||
|
"$@"
|
||||||
|
}
|
||||||
|
|
||||||
|
run_tests() {
|
||||||
|
local version="$1"
|
||||||
|
local check_tasks
|
||||||
|
|
||||||
|
mapfile -t check_tasks < <(module_tasks check)
|
||||||
|
|
||||||
|
log "Testing ZomboidForge ${version}: ${MODULES[*]}"
|
||||||
|
run_gradle "${version}" :core:check "${check_tasks[@]}"
|
||||||
|
}
|
||||||
|
|
||||||
|
publish() {
|
||||||
|
local version="$1"
|
||||||
|
local publish_tasks
|
||||||
|
|
||||||
|
if [[ "${version}" == *-* ]]; then
|
||||||
|
log "${version} is a pre-release version; nothing is published."
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
mapfile -t publish_tasks < <(module_tasks publishAllPublicationsToGiteaRepository)
|
||||||
|
|
||||||
|
log "Publishing ZomboidForge ${version}"
|
||||||
|
run_gradle "${version}" "${publish_tasks[@]}"
|
||||||
|
log "Published ${MODULES[*]} ${version}"
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
local step="${1:-}"
|
||||||
|
local version
|
||||||
|
|
||||||
|
version="$(release_tag_version)"
|
||||||
|
if [[ -z "${version}" ]]; then
|
||||||
|
log "HEAD has no v* git tag (not a release commit, or a shallow clone without tags?); nothing to publish."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
case "${step}" in
|
||||||
|
test)
|
||||||
|
run_tests "${version}"
|
||||||
|
;;
|
||||||
|
publish)
|
||||||
|
publish "${version}"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
log "Usage: ci/publish.sh test|publish"
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
+61
-26
@@ -1,22 +1,29 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
#
|
#
|
||||||
# Builds the ZomboidForge image for one Project Zomboid version and optionally
|
# Builds the ZomboidForge image for the current build of a Steam branch and optionally
|
||||||
# publishes it. Published tags:
|
# publishes it. Published tags:
|
||||||
#
|
#
|
||||||
# <forge>-pz<pz>-build<steam_buildid> immutable; never overwritten
|
# <forge>-pz<major.minor.build> written once per ZomboidForge and Project Zomboid version
|
||||||
# <forge>-pz<pz> moves to the newest Steam build of that version
|
# <forge>-pz<major.minor> moves to the newest hotfix of that minor version
|
||||||
# latest only with LATEST=true
|
# latest only with LATEST=true
|
||||||
#
|
#
|
||||||
# <forge> is the newest v* git tag reachable from HEAD, without the "v" (v0.2.0 -> 0.2.0).
|
# <major.minor.build> is the version the branch's server jar reports, read before the full
|
||||||
# A pre-release version (containing "-", e.g. 0.2.0-rc.1) is built and verified but never
|
# build (Dockerfile stage game-version, which downloads only the jar).
|
||||||
# published. Without any v* tag the version is "0.0.0-prerelease".
|
|
||||||
#
|
#
|
||||||
# Nothing is built when the immutable tag already exists in the registry.
|
# <forge> is the v* git tag on HEAD, without the "v" (v0.2.0 -> 0.2.0). When HEAD has no such
|
||||||
|
# tag, it is the git describe version of HEAD (0.2.0-3-g1a2b3c4: 3 commits after v0.2.0).
|
||||||
|
# A pre-release version (containing "-", e.g. 0.2.0-rc.1 or 0.2.0-3-g1a2b3c4) is built and
|
||||||
|
# verified but never published. Without any v* tag the version is "0.0.0-prerelease".
|
||||||
|
#
|
||||||
|
# Nothing is built when <forge>-pz<major.minor.build> already exists in the registry. The
|
||||||
|
# server only admits clients with the same major.minor.build, so every hotfix (42.21.1 ->
|
||||||
|
# 42.21.2) gets an image; a new Steam build with an unchanged version does not.
|
||||||
#
|
#
|
||||||
# Environment:
|
# Environment:
|
||||||
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
|
# IMAGE Image name without tag, e.g. git.security-command.org/overlord/zomboidforge
|
||||||
# PZ_BRANCH Steam branch. Default: public
|
# PZ_BRANCH Steam branch. Default: public
|
||||||
# PZ_VERSION Expected Project Zomboid version. Default: pz.version in gradle.properties
|
# PZ_VERSION Accepted Project Zomboid versions ("42": every Build 42 version).
|
||||||
|
# Default: pz.version in gradle.properties
|
||||||
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only)
|
# PUBLISH true: push the tags (not for pre-release versions). Default: false (build and verify only)
|
||||||
# LATEST true: also push "latest". Default: false
|
# LATEST true: also push "latest". Default: false
|
||||||
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
|
# CONTAINER_ENGINE docker or podman. Default: docker if installed, else podman
|
||||||
@@ -63,12 +70,15 @@ gradle_property() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# Prints the forge version: the newest v* tag reachable from HEAD without its "v",
|
# Prints the forge version without the "v": the v* tag on HEAD, else the git describe version
|
||||||
# or nothing when the repository has no such tag.
|
# of HEAD relative to the newest reachable v* tag (v0.2.0-3-g1a2b3c4), or nothing when the
|
||||||
|
# repository has no such tag.
|
||||||
release_tag_version() {
|
release_tag_version() {
|
||||||
local tag
|
local tag
|
||||||
|
|
||||||
if tag="$(git -C "${REPO_ROOT}" describe --tags --abbrev=0 --match 'v*' 2> /dev/null)"; then
|
if tag="$(git -C "${REPO_ROOT}" describe --tags --exact-match --match 'v*' 2> /dev/null)"; then
|
||||||
|
echo "${tag#v}"
|
||||||
|
elif tag="$(git -C "${REPO_ROOT}" describe --tags --match 'v*' 2> /dev/null)"; then
|
||||||
echo "${tag#v}"
|
echo "${tag#v}"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
@@ -78,6 +88,22 @@ image_exists() {
|
|||||||
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
|
"$(container_engine)" manifest inspect "${reference}" > /dev/null 2>&1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Prints the game version of the branch's current server jar, e.g. 42.21.0. Downloads only
|
||||||
|
# the jar; the result stays cached until the build ID changes.
|
||||||
|
read_game_version() {
|
||||||
|
local build_id="$1"
|
||||||
|
local image
|
||||||
|
|
||||||
|
image="$("$(container_engine)" build --quiet \
|
||||||
|
--platform linux/amd64 \
|
||||||
|
--target game-version \
|
||||||
|
--build-arg "PZ_BRANCH=${PZ_BRANCH}" \
|
||||||
|
--build-arg "STEAM_BUILDID=${build_id}" \
|
||||||
|
"${REPO_ROOT}")"
|
||||||
|
|
||||||
|
"$(container_engine)" run --rm --entrypoint cat "${image}" /game-version
|
||||||
|
}
|
||||||
|
|
||||||
build_image() {
|
build_image() {
|
||||||
local reference="$1"
|
local reference="$1"
|
||||||
local forge_version="$2"
|
local forge_version="$2"
|
||||||
@@ -119,8 +145,9 @@ push_as() {
|
|||||||
main() {
|
main() {
|
||||||
local forge_version
|
local forge_version
|
||||||
local publish="${REQUESTED_PUBLISH}"
|
local publish="${REQUESTED_PUBLISH}"
|
||||||
local pz_version
|
local pz_prefix
|
||||||
local build_id
|
local build_id
|
||||||
|
local game_version
|
||||||
|
|
||||||
forge_version="$(release_tag_version)"
|
forge_version="$(release_tag_version)"
|
||||||
if [[ -z "${forge_version}" ]]; then
|
if [[ -z "${forge_version}" ]]; then
|
||||||
@@ -132,31 +159,39 @@ main() {
|
|||||||
log "${forge_version} is a pre-release version; nothing will be published."
|
log "${forge_version} is a pre-release version; nothing will be published."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
pz_version="${PZ_VERSION:-$(gradle_property pz.version)}"
|
pz_prefix="${PZ_VERSION:-$(gradle_property pz.version)}"
|
||||||
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
|
build_id="$("${REPO_ROOT}/ci/steam-buildid.sh" "${PZ_BRANCH}")"
|
||||||
|
game_version="$(read_game_version "${build_id}")"
|
||||||
|
log "ZomboidForge ${forge_version}, Project Zomboid ${game_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
|
||||||
|
|
||||||
local immutable_tag="${IMAGE}:${forge_version}-pz${pz_version}-build${build_id}"
|
# Checked here as well as by the patcher, to fail before the full download.
|
||||||
local version_tag="${IMAGE}:${forge_version}-pz${pz_version}"
|
if [[ "${game_version}" != "${pz_prefix}" && "${game_version}" != "${pz_prefix}."* ]]; then
|
||||||
log "ZomboidForge ${forge_version}, Project Zomboid ${pz_version}, Steam branch ${PZ_BRANCH} build ${build_id}"
|
log "Steam branch ${PZ_BRANCH} has Project Zomboid ${game_version}; the build accepts ${pz_prefix}."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
if [[ "${publish}" == true ]] && image_exists "${immutable_tag}"; then
|
local version_tag="${IMAGE}:${forge_version}-pz${game_version}"
|
||||||
log "${immutable_tag} is already published; nothing to do."
|
# 42.21.2 -> 42.21
|
||||||
|
local minor_tag="${IMAGE}:${forge_version}-pz${game_version%.*}"
|
||||||
|
|
||||||
|
if [[ "${publish}" == true ]] && image_exists "${version_tag}"; then
|
||||||
|
log "${version_tag} is already published; nothing to do."
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
build_image "${immutable_tag}" "${forge_version}" "${pz_version}" "${build_id}"
|
build_image "${version_tag}" "${forge_version}" "${game_version}" "${build_id}"
|
||||||
verify_build_id "${immutable_tag}" "${build_id}"
|
verify_build_id "${version_tag}" "${build_id}"
|
||||||
|
|
||||||
if [[ "${publish}" != true ]]; then
|
if [[ "${publish}" != true ]]; then
|
||||||
log "Built ${immutable_tag} (not published)"
|
log "Built ${version_tag} (not published)"
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
"$(container_engine)" push "${immutable_tag}"
|
"$(container_engine)" push "${version_tag}"
|
||||||
log "Pushed ${immutable_tag}"
|
log "Pushed ${version_tag}"
|
||||||
push_as "${immutable_tag}" "${version_tag}"
|
push_as "${version_tag}" "${minor_tag}"
|
||||||
if [[ "${LATEST}" == true ]]; then
|
if [[ "${LATEST}" == true ]]; then
|
||||||
push_as "${immutable_tag}" "${IMAGE}:latest"
|
push_as "${version_tag}" "${IMAGE}:latest"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ set -o nounset
|
|||||||
set -o pipefail
|
set -o pipefail
|
||||||
|
|
||||||
readonly APP_ID="380870"
|
readonly APP_ID="380870"
|
||||||
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13"
|
readonly STEAMCMD_IMAGE="docker.io/steamcmd/steamcmd:debian-13@sha256:b0b49ef3101c304ed6e3fbc3ea930b2940d7c489563a1ebac524ad5bb46d336d"
|
||||||
|
|
||||||
readonly BRANCH="$1"
|
readonly BRANCH="$1"
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
implementation(project(":api"))
|
||||||
implementation(project(":patcher"))
|
implementation(project(":patcher"))
|
||||||
implementation(libs.bundles.asm)
|
implementation(libs.bundles.asm)
|
||||||
|
|
||||||
|
|||||||
+6
-5
@@ -1,10 +1,7 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42;
|
package dev.overlord.zomboidforge.compat.b42;
|
||||||
|
|
||||||
import dev.overlord.zomboidforge.compat.b42.patches.ServerStartedPatch;
|
import dev.overlord.zomboidforge.compat.b42.patches.*;
|
||||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoGameCharacterStateMachinePerformancePatch;
|
import dev.overlord.zomboidforge.compat.b42.perf.*;
|
||||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieNetworkComponentPerformancePatch;
|
|
||||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieSpotChancePerformancePatch;
|
|
||||||
import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieVehiclePerformancePatch;
|
|
||||||
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||||
import dev.overlord.zomboidforge.patcher.PatchSet;
|
import dev.overlord.zomboidforge.patcher.PatchSet;
|
||||||
|
|
||||||
@@ -16,7 +13,11 @@ import java.util.List;
|
|||||||
public final class B42PatchSet implements PatchSet
|
public final class B42PatchSet implements PatchSet
|
||||||
{
|
{
|
||||||
private static final List<ClassPatch> PATCHES = List.of(
|
private static final List<ClassPatch> PATCHES = List.of(
|
||||||
|
new ServerLoadPatch(),
|
||||||
new ServerStartedPatch(),
|
new ServerStartedPatch(),
|
||||||
|
new ServerTickPatch(),
|
||||||
|
new ServerStoppingPatch(),
|
||||||
|
new BackupStoragePatch(),
|
||||||
new IsoZombieVehiclePerformancePatch(),
|
new IsoZombieVehiclePerformancePatch(),
|
||||||
new IsoZombieNetworkComponentPerformancePatch(),
|
new IsoZombieNetworkComponentPerformancePatch(),
|
||||||
new IsoZombieSpotChancePerformancePatch(),
|
new IsoZombieSpotChancePerformancePatch(),
|
||||||
|
|||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
|
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Hook;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.InsnList;
|
||||||
|
import org.objectweb.asm.tree.InsnNode;
|
||||||
|
import org.objectweb.asm.tree.LabelNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
import org.objectweb.asm.tree.TryCatchBlockNode;
|
||||||
|
import org.objectweb.asm.tree.VarInsnNode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps {@code ZipBackup.makeBackupFile(String, BackupTypes)}, which zips the save folder
|
||||||
|
* including {@code zomboidforge.db}, so that storage writes wait during a backup:
|
||||||
|
*
|
||||||
|
* <pre>{@code
|
||||||
|
* private static void makeBackupFile(String serverName, BackupTypes type)
|
||||||
|
* {
|
||||||
|
* StorageHooks.backupRunning(true);
|
||||||
|
* try { zomboidForge$makeBackupFile(serverName, type); }
|
||||||
|
* finally { StorageHooks.backupRunning(false); }
|
||||||
|
* }
|
||||||
|
* }</pre>
|
||||||
|
*
|
||||||
|
* The vanilla method is renamed to {@code zomboidForge$makeBackupFile} and stays unchanged. It
|
||||||
|
* reads the zipped files until {@code ParallelScatterZipCreator.writeTo} returns and catches its
|
||||||
|
* own exceptions, so only a wrapper around the whole method covers the entire backup.
|
||||||
|
*/
|
||||||
|
public final class BackupStoragePatch implements ClassPatch
|
||||||
|
{
|
||||||
|
private static final String TARGET = "zombie/core/backup/ZipBackup";
|
||||||
|
private static final String RENAMED = "zomboidForge$makeBackupFile";
|
||||||
|
|
||||||
|
private static final Anchor.Method ANCHOR = new Anchor.Method(
|
||||||
|
"makeBackupFile", "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V"
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Hook HOOK = new Hook(
|
||||||
|
"dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks", "backupRunning", "(Z)V"
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String target() { return BackupStoragePatch.TARGET; }
|
||||||
|
@Override
|
||||||
|
public Anchor.Method anchor() { return BackupStoragePatch.ANCHOR; }
|
||||||
|
@Override
|
||||||
|
public Hook hook() { return BackupStoragePatch.HOOK; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void apply(ClassNode node)
|
||||||
|
{
|
||||||
|
MethodNode original = BackupStoragePatch.ANCHOR.resolve(node);
|
||||||
|
|
||||||
|
if ((original.access & Opcodes.ACC_STATIC) == 0)
|
||||||
|
throw new IllegalStateException("'" + node.name + "." + original.name + original.desc + "' is not static.");
|
||||||
|
|
||||||
|
boolean taken = node.methods.stream().anyMatch(method -> method.name.equals(BackupStoragePatch.RENAMED));
|
||||||
|
if (taken) throw new IllegalStateException("'" + node.name + "' already has a method '" + BackupStoragePatch.RENAMED + "'.");
|
||||||
|
|
||||||
|
MethodNode wrapper = new MethodNode(original.access, original.name, original.desc, original.signature, original.exceptions.toArray(String[]::new));
|
||||||
|
original.name = BackupStoragePatch.RENAMED;
|
||||||
|
|
||||||
|
BackupStoragePatch.wrap(node.name, original.desc, wrapper);
|
||||||
|
node.methods.add(wrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code hook(true); try { renamed(args); } finally { hook(false); }} */
|
||||||
|
private static void wrap(String owner, String desc, MethodNode wrapper)
|
||||||
|
{
|
||||||
|
Type[] arguments = Type.getArgumentTypes(desc);
|
||||||
|
int thrown = arguments.length;
|
||||||
|
LabelNode start = new LabelNode();
|
||||||
|
LabelNode end = new LabelNode();
|
||||||
|
LabelNode handler = new LabelNode();
|
||||||
|
InsnList code = wrapper.instructions;
|
||||||
|
|
||||||
|
for (Type argument : arguments) {
|
||||||
|
if (argument.getSize() != 1) throw new IllegalStateException("'" + owner + "." + BackupStoragePatch.ANCHOR.name() + desc + "' has a wide argument; the wrapper only passes one-slot arguments.");
|
||||||
|
}
|
||||||
|
|
||||||
|
code.add(BackupStoragePatch.hook(true));
|
||||||
|
code.add(start);
|
||||||
|
|
||||||
|
for (int i = 0; i < arguments.length; i++) code.add(new VarInsnNode(arguments[i].getOpcode(Opcodes.ILOAD), i));
|
||||||
|
|
||||||
|
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, owner, BackupStoragePatch.RENAMED, desc, false));
|
||||||
|
code.add(end);
|
||||||
|
code.add(BackupStoragePatch.hook(false));
|
||||||
|
code.add(new InsnNode(Opcodes.RETURN));
|
||||||
|
|
||||||
|
code.add(handler);
|
||||||
|
code.add(new VarInsnNode(Opcodes.ASTORE, thrown));
|
||||||
|
code.add(BackupStoragePatch.hook(false));
|
||||||
|
code.add(new VarInsnNode(Opcodes.ALOAD, thrown));
|
||||||
|
code.add(new InsnNode(Opcodes.ATHROW));
|
||||||
|
|
||||||
|
wrapper.tryCatchBlocks.add(new TryCatchBlockNode(start, end, handler, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static InsnList hook(boolean running)
|
||||||
|
{
|
||||||
|
InsnList code = new InsnList();
|
||||||
|
|
||||||
|
code.add(new InsnNode(running ? Opcodes.ICONST_1 : Opcodes.ICONST_0));
|
||||||
|
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, BackupStoragePatch.HOOK.owner(), BackupStoragePatch.HOOK.name(), BackupStoragePatch.HOOK.desc(), false));
|
||||||
|
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
}
|
||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
|
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Hook;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.FieldInsnNode;
|
||||||
|
import org.objectweb.asm.tree.FieldNode;
|
||||||
|
import org.objectweb.asm.tree.InsnList;
|
||||||
|
import org.objectweb.asm.tree.InsnNode;
|
||||||
|
import org.objectweb.asm.tree.JumpInsnNode;
|
||||||
|
import org.objectweb.asm.tree.LabelNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls {@code ServerHooks.onLoad()} in {@code GameServer.main}, directly after
|
||||||
|
* {@code ServerOptions.instance.init()}, and stops the server when it returns {@code false}:
|
||||||
|
*
|
||||||
|
* <pre>{@code
|
||||||
|
* if (!ServerHooks.onLoad()) {
|
||||||
|
* Runtime.getRuntime().removeShutdownHook(shutdownHook);
|
||||||
|
* System.exit(1);
|
||||||
|
* }
|
||||||
|
* }</pre>
|
||||||
|
*
|
||||||
|
* The vanilla shutdown hook saves the map on every JVM exit; before the world is loaded that
|
||||||
|
* save fails with a {@code NullPointerException} in {@code IsoMetaGrid.save()}. The inserted
|
||||||
|
* code is part of {@code GameServer}, so it reads the private field {@code shutdownHook}
|
||||||
|
* directly.
|
||||||
|
*/
|
||||||
|
public final class ServerLoadPatch implements ClassPatch
|
||||||
|
{
|
||||||
|
private static final String TARGET = "zombie/network/GameServer";
|
||||||
|
|
||||||
|
private static final String SHUTDOWN_HOOK = "shutdownHook";
|
||||||
|
private static final String SHUTDOWN_HOOK_DESC = "Ljava/lang/Thread;";
|
||||||
|
|
||||||
|
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||||
|
new Anchor.Method("main", "([Ljava/lang/String;)V"),
|
||||||
|
"zombie/network/ServerOptions", "init", "()V"
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Hook HOOK = new Hook(
|
||||||
|
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onLoad", "()Z"
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String target() { return ServerLoadPatch.TARGET; }
|
||||||
|
@Override
|
||||||
|
public Anchor.Call anchor() { return ServerLoadPatch.ANCHOR; }
|
||||||
|
@Override
|
||||||
|
public Hook hook() { return ServerLoadPatch.HOOK; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void apply(ClassNode node)
|
||||||
|
{
|
||||||
|
ServerLoadPatch.requireShutdownHookField(node);
|
||||||
|
|
||||||
|
MethodInsnNode init = ServerLoadPatch.ANCHOR.resolve(node);
|
||||||
|
ServerLoadPatch.ANCHOR.in().resolve(node).instructions.insert(init, ServerLoadPatch.abortUnlessLoaded());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The abort path runs only when a mod fails, so a missing field would otherwise go unnoticed until then. */
|
||||||
|
private static void requireShutdownHookField(ClassNode node)
|
||||||
|
{
|
||||||
|
boolean found = node.fields.stream().anyMatch(ServerLoadPatch::isShutdownHook);
|
||||||
|
|
||||||
|
if (!found) throw new IllegalStateException("Expected the static field '" + node.name + "." + ServerLoadPatch.SHUTDOWN_HOOK + " " + ServerLoadPatch.SHUTDOWN_HOOK_DESC + "'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isShutdownHook(FieldNode field)
|
||||||
|
{
|
||||||
|
return field.name.equals(ServerLoadPatch.SHUTDOWN_HOOK)
|
||||||
|
&& field.desc.equals(ServerLoadPatch.SHUTDOWN_HOOK_DESC)
|
||||||
|
&& (field.access & Opcodes.ACC_STATIC) != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static InsnList abortUnlessLoaded()
|
||||||
|
{
|
||||||
|
InsnList code = new InsnList();
|
||||||
|
LabelNode loaded = new LabelNode();
|
||||||
|
|
||||||
|
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, ServerLoadPatch.HOOK.owner(), ServerLoadPatch.HOOK.name(), ServerLoadPatch.HOOK.desc(), false));
|
||||||
|
code.add(new JumpInsnNode(Opcodes.IFNE, loaded));
|
||||||
|
|
||||||
|
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false));
|
||||||
|
code.add(new FieldInsnNode(Opcodes.GETSTATIC, ServerLoadPatch.TARGET, ServerLoadPatch.SHUTDOWN_HOOK, ServerLoadPatch.SHUTDOWN_HOOK_DESC));
|
||||||
|
code.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/lang/Runtime", "removeShutdownHook", "(Ljava/lang/Thread;)Z", false));
|
||||||
|
code.add(new InsnNode(Opcodes.POP));
|
||||||
|
|
||||||
|
code.add(new InsnNode(Opcodes.ICONST_1));
|
||||||
|
code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "java/lang/System", "exit", "(I)V", false));
|
||||||
|
|
||||||
|
code.add(loaded);
|
||||||
|
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
|
import dev.overlord.zomboidforge.patcher.ClassPatch;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Hook;
|
||||||
|
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.FieldInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls {@code ServerHooks.onStopping()} in the vanilla shutdown hook {@code GameServer$1.run()},
|
||||||
|
* between {@code GameServer.done = true} and {@code ServerMap.instance.QueuedQuit()}, which saves
|
||||||
|
* the world.
|
||||||
|
*
|
||||||
|
* <p>{@code GameServer$1} is the only caller of {@code QueuedQuit()}. The {@code quit} command
|
||||||
|
* only sets {@code ServerMap.queuedQuit}; {@code ServerMap.preupdate()} then calls
|
||||||
|
* {@code System.exit(0)}, so the save runs in the shutdown hook as it does for SIGTERM and SIGINT.
|
||||||
|
*/
|
||||||
|
public final class ServerStoppingPatch implements ClassPatch
|
||||||
|
{
|
||||||
|
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||||
|
|
||||||
|
/** {@code GameServer.done = true; ServerMap.instance.QueuedQuit();} */
|
||||||
|
private static final Anchor.Sequence ANCHOR = new Anchor.Sequence(
|
||||||
|
new Anchor.Method("run", "()V"),
|
||||||
|
new Anchor.Instruction.Constant(1),
|
||||||
|
new Anchor.Instruction.Opcode(Opcodes.PUTSTATIC),
|
||||||
|
new Anchor.Instruction.Opcode(Opcodes.GETSTATIC),
|
||||||
|
new Anchor.Instruction.Invoke("zombie/network/ServerMap", "QueuedQuit", "()V")
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Hook HOOK = new Hook(
|
||||||
|
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onStopping", "()V"
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String target() { return ServerStoppingPatch.GAME_SERVER + "$1"; }
|
||||||
|
@Override
|
||||||
|
public Anchor.Sequence anchor() { return ServerStoppingPatch.ANCHOR; }
|
||||||
|
@Override
|
||||||
|
public Hook hook() { return ServerStoppingPatch.HOOK; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void apply(ClassNode node)
|
||||||
|
{
|
||||||
|
List<AbstractInsnNode> matched = ServerStoppingPatch.ANCHOR.resolve(node);
|
||||||
|
FieldInsnNode done = (FieldInsnNode) matched.get(1);
|
||||||
|
|
||||||
|
if (!done.owner.equals(ServerStoppingPatch.GAME_SERVER) || !done.name.equals("done"))
|
||||||
|
throw new IllegalStateException("'" + node.name + ".run()V' sets '" + done.owner + "." + done.name + "' before 'QueuedQuit()', expected '" + ServerStoppingPatch.GAME_SERVER + ".done'.");
|
||||||
|
|
||||||
|
ServerStoppingPatch.ANCHOR.in().resolve(node).instructions.insert(
|
||||||
|
done, new MethodInsnNode(
|
||||||
|
Opcodes.INVOKESTATIC,
|
||||||
|
ServerStoppingPatch.HOOK.owner(),
|
||||||
|
ServerStoppingPatch.HOOK.name(),
|
||||||
|
ServerStoppingPatch.HOOK.desc(),
|
||||||
|
false
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Hook;
|
||||||
|
import dev.overlord.zomboidforge.patcher.Patches.HookInjectionPatch;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls {@code ServerHooks.onTick()} in the main loop of {@code GameServer.main}, directly after
|
||||||
|
* {@code ServerMap.instance.preupdate()} at the start of the frame branch. The {@code while (!done)}
|
||||||
|
* loop itself also iterates while the update limiter skips a frame; the frame branch runs once
|
||||||
|
* per game frame.
|
||||||
|
*/
|
||||||
|
public final class ServerTickPatch extends HookInjectionPatch
|
||||||
|
{
|
||||||
|
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||||
|
new Anchor.Method("main", "([Ljava/lang/String;)V"),
|
||||||
|
"zombie/network/ServerMap", "preupdate", "()V"
|
||||||
|
);
|
||||||
|
|
||||||
|
private static final Hook HOOK = new Hook(
|
||||||
|
"dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks", "onTick", "()V"
|
||||||
|
);
|
||||||
|
|
||||||
|
public ServerTickPatch() {
|
||||||
|
super("zombie/network/GameServer", ServerTickPatch.ANCHOR, ServerTickPatch.HOOK);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
|
||||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||||
|
|
||||||
import org.objectweb.asm.Opcodes;
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
|
||||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||||
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
|
||||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||||
|
|
||||||
import org.objectweb.asm.Opcodes;
|
import org.objectweb.asm.Opcodes;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
|
||||||
import dev.overlord.zomboidforge.patcher.Hook;
|
import dev.overlord.zomboidforge.patcher.Hook;
|
||||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||||
|
|
||||||
|
|||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
|
||||||
|
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.Type;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||||
|
import static org.objectweb.asm.Opcodes.ATHROW;
|
||||||
|
import static org.objectweb.asm.Opcodes.DUP;
|
||||||
|
import static org.objectweb.asm.Opcodes.IFEQ;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||||
|
import static org.objectweb.asm.Opcodes.NEW;
|
||||||
|
import static org.objectweb.asm.Opcodes.RETURN;
|
||||||
|
import static org.objectweb.asm.Opcodes.V25;
|
||||||
|
|
||||||
|
class BackupStoragePatchTest
|
||||||
|
{
|
||||||
|
private static final String ZIP_BACKUP = "zombie/core/backup/ZipBackup";
|
||||||
|
private static final String TYPES = "zombie/core/backup/ZipBackup$BackupTypes";
|
||||||
|
private static final String DESC = "(Ljava/lang/String;L" + BackupStoragePatchTest.TYPES + ";)V";
|
||||||
|
private static final String CALLS = Type.getInternalName(BackupStoragePatchTest.Calls.class);
|
||||||
|
|
||||||
|
/** Stands in for {@code StorageHooks.backupRunning(boolean)} and records the calls. */
|
||||||
|
public static final class Calls
|
||||||
|
{
|
||||||
|
public static final List<String> LOG = new ArrayList<>();
|
||||||
|
|
||||||
|
private Calls() {}
|
||||||
|
|
||||||
|
public static void record(String call) { Calls.LOG.add(call); }
|
||||||
|
|
||||||
|
public static void backupRunning(boolean running) { Calls.LOG.add("backupRunning " + running); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code ZipBackup} with the vanilla method's shape:
|
||||||
|
*
|
||||||
|
* <pre>{@code
|
||||||
|
* private static void makeBackupFile(String serverName, BackupTypes type)
|
||||||
|
* {
|
||||||
|
* if (serverName.equals("fail")) throw new IllegalStateException("zip failed");
|
||||||
|
* Calls.record("backup " + serverName);
|
||||||
|
* }
|
||||||
|
* }</pre>
|
||||||
|
*/
|
||||||
|
private static ClassNode zipBackup()
|
||||||
|
{
|
||||||
|
ClassNode node = BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.ZIP_BACKUP);
|
||||||
|
|
||||||
|
MethodVisitor method = node.visitMethod(ACC_PRIVATE | ACC_STATIC, "makeBackupFile", BackupStoragePatchTest.DESC, null, null);
|
||||||
|
Label normal = new Label();
|
||||||
|
|
||||||
|
method.visitVarInsn(ALOAD, 0);
|
||||||
|
method.visitLdcInsn("fail");
|
||||||
|
method.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z", false);
|
||||||
|
method.visitJumpInsn(IFEQ, normal);
|
||||||
|
method.visitTypeInsn(NEW, "java/lang/IllegalStateException");
|
||||||
|
method.visitInsn(DUP);
|
||||||
|
method.visitLdcInsn("zip failed");
|
||||||
|
method.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalStateException", "<init>", "(Ljava/lang/String;)V", false);
|
||||||
|
method.visitInsn(ATHROW);
|
||||||
|
|
||||||
|
method.visitLabel(normal);
|
||||||
|
method.visitVarInsn(ALOAD, 0);
|
||||||
|
method.visitMethodInsn(INVOKESTATIC, BackupStoragePatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||||
|
method.visitInsn(RETURN);
|
||||||
|
method.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ClassNode emptyClass(String name)
|
||||||
|
{
|
||||||
|
ClassNode node = new ClassNode();
|
||||||
|
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||||
|
|
||||||
|
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||||
|
init.visitVarInsn(ALOAD, 0);
|
||||||
|
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||||
|
init.visitInsn(RETURN);
|
||||||
|
init.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Patches {@code ZipBackup}, points the hook at {@link Calls}, and returns {@code makeBackupFile}. */
|
||||||
|
private static Method patched() throws ReflectiveOperationException
|
||||||
|
{
|
||||||
|
BackupStoragePatch patch = new BackupStoragePatch();
|
||||||
|
ClassNode zipBackup = BackupStoragePatchTest.zipBackup();
|
||||||
|
|
||||||
|
patch.apply(zipBackup);
|
||||||
|
CallRedirect.redirect(zipBackup, patch.hook().owner(), patch.hook().name(), BackupStoragePatchTest.CALLS);
|
||||||
|
|
||||||
|
ClassDefiner definer = new ClassDefiner();
|
||||||
|
Class<?> types = definer.define(BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.TYPES));
|
||||||
|
Class<?> loaded = definer.define(zipBackup);
|
||||||
|
|
||||||
|
Method method = loaded.getDeclaredMethod("makeBackupFile", String.class, types);
|
||||||
|
method.setAccessible(true);
|
||||||
|
|
||||||
|
BackupStoragePatchTest.Calls.LOG.clear();
|
||||||
|
return method;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void anchorMatchesTheTarget()
|
||||||
|
{
|
||||||
|
new BackupStoragePatch().anchor().verify(BackupStoragePatchTest.zipBackup());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void callsTheHookAroundTheBackup() throws ReflectiveOperationException
|
||||||
|
{
|
||||||
|
BackupStoragePatchTest.patched().invoke(null, "server", null);
|
||||||
|
|
||||||
|
assertEquals(List.of("backupRunning true", "server", "backupRunning false"), BackupStoragePatchTest.Calls.LOG);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void callsTheHookAfterAFailedBackupToo() throws ReflectiveOperationException
|
||||||
|
{
|
||||||
|
Method method = BackupStoragePatchTest.patched();
|
||||||
|
|
||||||
|
InvocationTargetException e = assertThrows(InvocationTargetException.class, () -> method.invoke(null, "fail", null));
|
||||||
|
|
||||||
|
assertInstanceOf(IllegalStateException.class, e.getCause());
|
||||||
|
assertEquals(List.of("backupRunning true", "backupRunning false"), BackupStoragePatchTest.Calls.LOG);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failsWhenTheRenamedMethodExists()
|
||||||
|
{
|
||||||
|
ClassNode zipBackup = BackupStoragePatchTest.zipBackup();
|
||||||
|
zipBackup.visitMethod(ACC_PRIVATE | ACC_STATIC, "zomboidForge$makeBackupFile", "()V", null, null);
|
||||||
|
|
||||||
|
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BackupStoragePatch().apply(zipBackup));
|
||||||
|
assertEquals("'zombie/core/backup/ZipBackup' already has a method 'zomboidForge$makeBackupFile'.", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
+204
@@ -0,0 +1,204 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
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.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||||
|
import static org.objectweb.asm.Opcodes.DUP;
|
||||||
|
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||||
|
import static org.objectweb.asm.Opcodes.NEW;
|
||||||
|
import static org.objectweb.asm.Opcodes.PUTSTATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.RETURN;
|
||||||
|
import static org.objectweb.asm.Opcodes.V25;
|
||||||
|
|
||||||
|
class ServerLoadPatchTest
|
||||||
|
{
|
||||||
|
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||||
|
private static final String SERVER_OPTIONS = "zombie/network/ServerOptions";
|
||||||
|
private static final String CALLS = Type.getInternalName(ServerLoadPatchTest.Calls.class);
|
||||||
|
|
||||||
|
/** Stands in for {@code ServerHooks.onLoad()} and {@code System.exit}, and records the calls. */
|
||||||
|
public static final class Calls
|
||||||
|
{
|
||||||
|
public static final List<String> LOG = new ArrayList<>();
|
||||||
|
|
||||||
|
public static boolean loaded;
|
||||||
|
|
||||||
|
private Calls() {}
|
||||||
|
|
||||||
|
public static void record(String call) { Calls.LOG.add(call); }
|
||||||
|
|
||||||
|
public static boolean onLoad()
|
||||||
|
{
|
||||||
|
Calls.LOG.add("onLoad");
|
||||||
|
return Calls.loaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void exit(int status) { Calls.LOG.add("exit " + status); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private record Run(List<String> calls, Thread shutdownHook) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code GameServer} with the parts of {@code main} the patch depends on:
|
||||||
|
*
|
||||||
|
* <pre>{@code
|
||||||
|
* private static Thread shutdownHook = new Thread(); // only with withShutdownHook
|
||||||
|
*
|
||||||
|
* static { Runtime.getRuntime().addShutdownHook(shutdownHook); }
|
||||||
|
*
|
||||||
|
* public static void main(String[] args)
|
||||||
|
* {
|
||||||
|
* ServerOptions.instance.init();
|
||||||
|
* Calls.record("after");
|
||||||
|
* }
|
||||||
|
* }</pre>
|
||||||
|
*/
|
||||||
|
private static ClassNode gameServer(boolean withShutdownHook)
|
||||||
|
{
|
||||||
|
ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.GAME_SERVER);
|
||||||
|
|
||||||
|
if (withShutdownHook) {
|
||||||
|
node.visitField(ACC_PRIVATE | ACC_STATIC, "shutdownHook", "Ljava/lang/Thread;", null, null);
|
||||||
|
|
||||||
|
MethodVisitor init = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
|
||||||
|
init.visitTypeInsn(NEW, "java/lang/Thread");
|
||||||
|
init.visitInsn(DUP);
|
||||||
|
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Thread", "<init>", "()V", false);
|
||||||
|
init.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;");
|
||||||
|
init.visitMethodInsn(INVOKESTATIC, "java/lang/Runtime", "getRuntime", "()Ljava/lang/Runtime;", false);
|
||||||
|
init.visitFieldInsn(GETSTATIC, ServerLoadPatchTest.GAME_SERVER, "shutdownHook", "Ljava/lang/Thread;");
|
||||||
|
init.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Runtime", "addShutdownHook", "(Ljava/lang/Thread;)V", false);
|
||||||
|
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, ServerLoadPatchTest.SERVER_OPTIONS, "instance", "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";");
|
||||||
|
main.visitMethodInsn(INVOKEVIRTUAL, ServerLoadPatchTest.SERVER_OPTIONS, "init", "()V", false);
|
||||||
|
main.visitLdcInsn("after");
|
||||||
|
main.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||||
|
main.visitInsn(RETURN);
|
||||||
|
main.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code ServerOptions} with {@code public static ServerOptions instance} and {@code init()} recording {@code "init"}. */
|
||||||
|
private static ClassNode serverOptions()
|
||||||
|
{
|
||||||
|
ClassNode node = ServerLoadPatchTest.emptyClass(ServerLoadPatchTest.SERVER_OPTIONS);
|
||||||
|
String desc = "L" + ServerLoadPatchTest.SERVER_OPTIONS + ";";
|
||||||
|
|
||||||
|
node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null);
|
||||||
|
|
||||||
|
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
|
||||||
|
clinit.visitTypeInsn(NEW, ServerLoadPatchTest.SERVER_OPTIONS);
|
||||||
|
clinit.visitInsn(DUP);
|
||||||
|
clinit.visitMethodInsn(INVOKESPECIAL, ServerLoadPatchTest.SERVER_OPTIONS, "<init>", "()V", false);
|
||||||
|
clinit.visitFieldInsn(PUTSTATIC, ServerLoadPatchTest.SERVER_OPTIONS, "instance", desc);
|
||||||
|
clinit.visitInsn(RETURN);
|
||||||
|
clinit.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "init", "()V", null, null);
|
||||||
|
init.visitLdcInsn("init");
|
||||||
|
init.visitMethodInsn(INVOKESTATIC, ServerLoadPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||||
|
init.visitInsn(RETURN);
|
||||||
|
init.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Public class with a public no-argument constructor. */
|
||||||
|
private static ClassNode emptyClass(String name)
|
||||||
|
{
|
||||||
|
ClassNode node = new ClassNode();
|
||||||
|
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||||
|
|
||||||
|
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||||
|
init.visitVarInsn(ALOAD, 0);
|
||||||
|
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||||
|
init.visitInsn(RETURN);
|
||||||
|
init.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Patches {@code GameServer}, points the hook and {@code System.exit} at {@link Calls}, and runs {@code main}. */
|
||||||
|
private static Run run(boolean loaded) throws ReflectiveOperationException
|
||||||
|
{
|
||||||
|
ServerLoadPatch patch = new ServerLoadPatch();
|
||||||
|
ClassNode gameServer = ServerLoadPatchTest.gameServer(true);
|
||||||
|
|
||||||
|
patch.apply(gameServer);
|
||||||
|
CallRedirect.redirect(gameServer, patch.hook().owner(), patch.hook().name(), ServerLoadPatchTest.CALLS);
|
||||||
|
CallRedirect.redirect(gameServer, "java/lang/System", "exit", ServerLoadPatchTest.CALLS);
|
||||||
|
|
||||||
|
ClassDefiner definer = new ClassDefiner();
|
||||||
|
definer.define(ServerLoadPatchTest.serverOptions());
|
||||||
|
Class<?> loadedClass = definer.define(gameServer);
|
||||||
|
|
||||||
|
ServerLoadPatchTest.Calls.LOG.clear();
|
||||||
|
ServerLoadPatchTest.Calls.loaded = loaded;
|
||||||
|
|
||||||
|
loadedClass.getMethod("main", String[].class).invoke(null, (Object) new String[0]);
|
||||||
|
|
||||||
|
Field shutdownHook = loadedClass.getDeclaredField("shutdownHook");
|
||||||
|
shutdownHook.setAccessible(true);
|
||||||
|
|
||||||
|
return new Run(List.copyOf(ServerLoadPatchTest.Calls.LOG), (Thread) shutdownHook.get(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void anchorMatchesTheTarget()
|
||||||
|
{
|
||||||
|
new ServerLoadPatch().anchor().verify(ServerLoadPatchTest.gameServer(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void continuesWhenTheHookReturnsTrue() throws ReflectiveOperationException
|
||||||
|
{
|
||||||
|
Run run = ServerLoadPatchTest.run(true);
|
||||||
|
|
||||||
|
assertEquals(List.of("init", "onLoad", "after"), run.calls());
|
||||||
|
assertTrue(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook is still registered.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void removesTheShutdownHookAndExitsWhenTheHookReturnsFalse() throws ReflectiveOperationException
|
||||||
|
{
|
||||||
|
Run run = ServerLoadPatchTest.run(false);
|
||||||
|
|
||||||
|
// The test double for System.exit returns, so "after" still runs.
|
||||||
|
assertEquals(List.of("init", "onLoad", "exit 1", "after"), run.calls());
|
||||||
|
assertFalse(Runtime.getRuntime().removeShutdownHook(run.shutdownHook()), "The vanilla shutdown hook was not removed.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failsWithoutTheShutdownHookField()
|
||||||
|
{
|
||||||
|
ClassNode gameServer = ServerLoadPatchTest.gameServer(false);
|
||||||
|
|
||||||
|
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerLoadPatch().apply(gameServer));
|
||||||
|
assertEquals("Expected the static field 'zombie/network/GameServer.shutdownHook Ljava/lang/Thread;'.", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
+173
@@ -0,0 +1,173 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect;
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ALOAD;
|
||||||
|
import static org.objectweb.asm.Opcodes.DUP;
|
||||||
|
import static org.objectweb.asm.Opcodes.GETSTATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.ICONST_1;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKESTATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||||
|
import static org.objectweb.asm.Opcodes.NEW;
|
||||||
|
import static org.objectweb.asm.Opcodes.PUTSTATIC;
|
||||||
|
import static org.objectweb.asm.Opcodes.RETURN;
|
||||||
|
import static org.objectweb.asm.Opcodes.V25;
|
||||||
|
|
||||||
|
class ServerStoppingPatchTest
|
||||||
|
{
|
||||||
|
private static final String GAME_SERVER = "zombie/network/GameServer";
|
||||||
|
private static final String SHUTDOWN_HOOK = "zombie/network/GameServer$1";
|
||||||
|
private static final String SERVER_MAP = "zombie/network/ServerMap";
|
||||||
|
private static final String CALLS = Type.getInternalName(ServerStoppingPatchTest.Calls.class);
|
||||||
|
|
||||||
|
/** Stands in for {@code ServerHooks.onStopping()} and records the calls. */
|
||||||
|
public static final class Calls
|
||||||
|
{
|
||||||
|
public static final List<String> LOG = new ArrayList<>();
|
||||||
|
|
||||||
|
/** {@code GameServer.done} of the class under test. */
|
||||||
|
public static Field done;
|
||||||
|
|
||||||
|
private Calls() {}
|
||||||
|
|
||||||
|
public static void record(String call) { Calls.LOG.add(call); }
|
||||||
|
|
||||||
|
public static void onStopping() throws IllegalAccessException { Calls.LOG.add("onStopping done=" + Calls.done.getBoolean(null)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code GameServer} with {@code public static boolean done} and {@code other}. */
|
||||||
|
private static ClassNode gameServer()
|
||||||
|
{
|
||||||
|
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.GAME_SERVER);
|
||||||
|
|
||||||
|
node.visitField(ACC_PUBLIC | ACC_STATIC, "done", "Z", null, null);
|
||||||
|
node.visitField(ACC_PUBLIC | ACC_STATIC, "other", "Z", null, null);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code ServerMap} with {@code public static ServerMap instance} and {@code QueuedQuit()} recording {@code "QueuedQuit"}. */
|
||||||
|
private static ClassNode serverMap()
|
||||||
|
{
|
||||||
|
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SERVER_MAP);
|
||||||
|
String desc = "L" + ServerStoppingPatchTest.SERVER_MAP + ";";
|
||||||
|
|
||||||
|
node.visitField(ACC_PUBLIC | ACC_STATIC, "instance", desc, null, null);
|
||||||
|
|
||||||
|
MethodVisitor clinit = node.visitMethod(ACC_STATIC, "<clinit>", "()V", null, null);
|
||||||
|
clinit.visitTypeInsn(NEW, ServerStoppingPatchTest.SERVER_MAP);
|
||||||
|
clinit.visitInsn(DUP);
|
||||||
|
clinit.visitMethodInsn(INVOKESPECIAL, ServerStoppingPatchTest.SERVER_MAP, "<init>", "()V", false);
|
||||||
|
clinit.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", desc);
|
||||||
|
clinit.visitInsn(RETURN);
|
||||||
|
clinit.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
MethodVisitor quit = node.visitMethod(ACC_PUBLIC, "QueuedQuit", "()V", null, null);
|
||||||
|
quit.visitLdcInsn("QueuedQuit");
|
||||||
|
quit.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||||
|
quit.visitInsn(RETURN);
|
||||||
|
quit.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code GameServer$1} with the part of {@code run()} the patch depends on:
|
||||||
|
*
|
||||||
|
* <pre>{@code
|
||||||
|
* public void run()
|
||||||
|
* {
|
||||||
|
* GameServer.<field> = true;
|
||||||
|
* ServerMap.instance.QueuedQuit();
|
||||||
|
* Calls.record("after");
|
||||||
|
* }
|
||||||
|
* }</pre>
|
||||||
|
*/
|
||||||
|
private static ClassNode shutdownHook(String field)
|
||||||
|
{
|
||||||
|
ClassNode node = ServerStoppingPatchTest.emptyClass(ServerStoppingPatchTest.SHUTDOWN_HOOK);
|
||||||
|
MethodVisitor run = node.visitMethod(ACC_PUBLIC, "run", "()V", null, null);
|
||||||
|
|
||||||
|
run.visitInsn(ICONST_1);
|
||||||
|
run.visitFieldInsn(PUTSTATIC, ServerStoppingPatchTest.GAME_SERVER, field, "Z");
|
||||||
|
run.visitFieldInsn(GETSTATIC, ServerStoppingPatchTest.SERVER_MAP, "instance", "L" + ServerStoppingPatchTest.SERVER_MAP + ";");
|
||||||
|
run.visitMethodInsn(INVOKEVIRTUAL, ServerStoppingPatchTest.SERVER_MAP, "QueuedQuit", "()V", false);
|
||||||
|
run.visitLdcInsn("after");
|
||||||
|
run.visitMethodInsn(INVOKESTATIC, ServerStoppingPatchTest.CALLS, "record", "(Ljava/lang/String;)V", false);
|
||||||
|
run.visitInsn(RETURN);
|
||||||
|
run.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Public class with a public no-argument constructor. */
|
||||||
|
private static ClassNode emptyClass(String name)
|
||||||
|
{
|
||||||
|
ClassNode node = new ClassNode();
|
||||||
|
node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||||
|
|
||||||
|
MethodVisitor init = node.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
|
||||||
|
init.visitVarInsn(ALOAD, 0);
|
||||||
|
init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||||
|
init.visitInsn(RETURN);
|
||||||
|
init.visitMaxs(0, 0);
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void anchorMatchesTheTarget()
|
||||||
|
{
|
||||||
|
new ServerStoppingPatch().anchor().verify(ServerStoppingPatchTest.shutdownHook("done"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void callsTheHookAfterDoneIsSetAndBeforeTheSave() throws ReflectiveOperationException
|
||||||
|
{
|
||||||
|
ServerStoppingPatch patch = new ServerStoppingPatch();
|
||||||
|
ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("done");
|
||||||
|
|
||||||
|
patch.apply(shutdownHook);
|
||||||
|
CallRedirect.redirect(shutdownHook, patch.hook().owner(), patch.hook().name(), ServerStoppingPatchTest.CALLS);
|
||||||
|
|
||||||
|
ClassDefiner definer = new ClassDefiner();
|
||||||
|
definer.define(ServerStoppingPatchTest.serverMap());
|
||||||
|
|
||||||
|
Class<?> gameServer = definer.define(ServerStoppingPatchTest.gameServer());
|
||||||
|
Class<?> loaded = definer.define(shutdownHook);
|
||||||
|
|
||||||
|
ServerStoppingPatchTest.Calls.LOG.clear();
|
||||||
|
ServerStoppingPatchTest.Calls.done = gameServer.getField("done");
|
||||||
|
|
||||||
|
loaded.getMethod("run").invoke(loaded.getConstructor().newInstance());
|
||||||
|
|
||||||
|
assertEquals(List.of("onStopping done=true", "QueuedQuit", "after"), ServerStoppingPatchTest.Calls.LOG);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failsWhenAnotherFieldIsSetBeforeTheSave()
|
||||||
|
{
|
||||||
|
ClassNode shutdownHook = ServerStoppingPatchTest.shutdownHook("other");
|
||||||
|
|
||||||
|
IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ServerStoppingPatch().apply(shutdownHook));
|
||||||
|
assertEquals(
|
||||||
|
"'zombie/network/GameServer$1.run()V' sets 'zombie/network/GameServer.other' before 'QueuedQuit()', expected 'zombie/network/GameServer.done'.",
|
||||||
|
e.getMessage()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.patches.support;
|
||||||
|
|
||||||
|
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||||
|
import org.objectweb.asm.tree.ClassNode;
|
||||||
|
import org.objectweb.asm.tree.MethodInsnNode;
|
||||||
|
import org.objectweb.asm.tree.MethodNode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Points calls in a patched test class at a test double, e.g. a hook or {@code System.exit}, so
|
||||||
|
* the patched code can run inside a test.
|
||||||
|
*/
|
||||||
|
public final class CallRedirect
|
||||||
|
{
|
||||||
|
private CallRedirect() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Changes the owner of every call to {@code owner.name} in {@code node} to {@code newOwner}.
|
||||||
|
* Fails when {@code node} contains no such call.
|
||||||
|
*/
|
||||||
|
public static void redirect(ClassNode node, String owner, String name, String newOwner)
|
||||||
|
{
|
||||||
|
int redirected = 0;
|
||||||
|
|
||||||
|
for (MethodNode method : node.methods) {
|
||||||
|
for (AbstractInsnNode instruction : method.instructions) {
|
||||||
|
if (instruction instanceof MethodInsnNode call && call.owner.equals(owner) && call.name.equals(name)) {
|
||||||
|
call.owner = newOwner;
|
||||||
|
redirected++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (redirected == 0) throw new IllegalStateException("No call to '" + owner + "." + name + "' in '" + node.name + "'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
|
||||||
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.objectweb.asm.ClassReader;
|
import org.objectweb.asm.ClassReader;
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.objectweb.asm.Label;
|
import org.objectweb.asm.Label;
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||||
|
|
||||||
import dev.overlord.zomboidforge.patcher.GameVersion;
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.objectweb.asm.ClassReader;
|
import org.objectweb.asm.ClassReader;
|
||||||
|
|||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.core.Forge;
|
||||||
|
|
||||||
|
/** The one {@link Forge} of the server, shared by the hook classes. */
|
||||||
|
public final class ForgeInstance
|
||||||
|
{
|
||||||
|
public static final Forge FORGE = Forge.fromSystemProperties();
|
||||||
|
|
||||||
|
private ForgeInstance() {}
|
||||||
|
}
|
||||||
+96
-3
@@ -1,17 +1,110 @@
|
|||||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
import dev.overlord.zomboidforge.api.ZomboidForge;
|
import dev.overlord.zomboidforge.api.ZomboidForge;
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||||
|
import dev.overlord.zomboidforge.core.storage.StorageDatabase;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||||
|
|
||||||
/** Hooks called by patched {@code zombie.network.GameServer} code. */
|
import zombie.ZomboidFileSystem;
|
||||||
|
import zombie.core.Core;
|
||||||
|
import zombie.network.GameServer;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hooks called by patched {@code zombie.network.GameServer} code and its shutdown hook
|
||||||
|
* {@code GameServer$1}. Exceptions are caught here: the main loop logs repeated exceptions only
|
||||||
|
* a limited number of times, and an exception in the shutdown hook would skip the world save.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("CallToPrintStackTrace")
|
||||||
public final class ServerHooks
|
public final class ServerHooks
|
||||||
{
|
{
|
||||||
private ServerHooks() {}
|
private ServerHooks() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called once on the main thread in {@code GameServer.main}, directly after
|
||||||
|
* {@code ServerOptions.instance.init()}: logging is set up, and the server name and cache
|
||||||
|
* directory are known. The Workshop download, the server database, Lua, and the world come
|
||||||
|
* later. Loads the mods.
|
||||||
|
*
|
||||||
|
* @return {@code false} to stop the server; the patched code then removes the vanilla
|
||||||
|
* shutdown hook and exits with code 1
|
||||||
|
*/
|
||||||
|
public static boolean onLoad()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
System.out.println("[ZomboidForge] " + ZomboidForge.VERSION + " loading mods.");
|
||||||
|
|
||||||
|
GameVersion game = GameVersion.parse(Core.getInstance().getGameAndBuildVersion());
|
||||||
|
Path gameJar = Path.of(Core.class.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||||
|
|
||||||
|
// The save folder ZipBackup zips. getCurrentSaveDir() depends on Core.gameMode, which GameServer.main sets to "Multiplayer" only later.
|
||||||
|
Path storage = Path.of(ZomboidFileSystem.instance.getCacheDir(), "Saves", "Multiplayer", GameServer.serverName, StorageDatabase.FILE);
|
||||||
|
|
||||||
|
ForgeInstance.FORGE.load(game, gameJar, ServerHooks.class.getClassLoader(), storage);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (ModLoadException e)
|
||||||
|
{
|
||||||
|
System.out.println("[ZomboidForge] Cannot load the mods, stopping the server:");
|
||||||
|
e.problems().forEach(problem -> System.out.println("[ZomboidForge] " + problem));
|
||||||
|
if (e.getCause() != null) e.getCause().printStackTrace();
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
catch (Throwable t)
|
||||||
|
{
|
||||||
|
System.out.println("[ZomboidForge] Startup failed, stopping the server.");
|
||||||
|
t.printStackTrace();
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Called once on the main thread, after the world is loaded, the network port is open, and
|
* 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.
|
* RCON is initialized; directly before the main loop starts.
|
||||||
*/
|
*/
|
||||||
public static void onServerStarted() {
|
public static void onServerStarted()
|
||||||
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ForgeInstance.FORGE.started();
|
||||||
|
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
|
||||||
|
}
|
||||||
|
catch (Throwable t) { t.printStackTrace(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called on the main thread for every frame of the main loop, directly after
|
||||||
|
* {@code ServerMap.instance.preupdate()}, inside the {@code frameStep} profiling probe. Not
|
||||||
|
* called while the update limiter skips a frame. Posts the tick event and runs the mods'
|
||||||
|
* queued main-thread tasks.
|
||||||
|
*/
|
||||||
|
public static void onTick()
|
||||||
|
{
|
||||||
|
try { ForgeInstance.FORGE.tick(); }
|
||||||
|
catch (Throwable t) { t.printStackTrace(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called once on the shutdown hook thread ({@code GameServer$1}), after
|
||||||
|
* {@code GameServer.done = true} and before {@code ServerMap.instance.QueuedQuit()} saves the
|
||||||
|
* world. Both ways the server stops lead here: the {@code quit} command makes
|
||||||
|
* {@code ServerMap.preupdate()} call {@code System.exit(0)}, and SIGTERM or SIGINT start the
|
||||||
|
* JVM shutdown directly. In the second case the main thread may still be inside a frame. Not
|
||||||
|
* called in soft-reset mode.
|
||||||
|
*/
|
||||||
|
public static void onStopping()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
System.out.println("[ZomboidForge] Server stopping.");
|
||||||
|
ForgeInstance.FORGE.stopping();
|
||||||
|
}
|
||||||
|
catch (Throwable t) { t.printStackTrace(); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.compat.b42.ForgeInstance;
|
||||||
|
|
||||||
|
/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */
|
||||||
|
@SuppressWarnings("CallToPrintStackTrace")
|
||||||
|
public final class StorageHooks
|
||||||
|
{
|
||||||
|
private StorageHooks() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called by the patched {@code ZipBackup.makeBackupFile} on the thread that makes the backup:
|
||||||
|
* with {@code true} before the vanilla method, with {@code false} after it, also when it threw.
|
||||||
|
* Storage writes wait in between, so the zipped {@code zomboidforge.db} is complete.
|
||||||
|
*/
|
||||||
|
public static void backupRunning(boolean running)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (running) ForgeInstance.FORGE.backupStarted();
|
||||||
|
else ForgeInstance.FORGE.backupFinished();
|
||||||
|
}
|
||||||
|
catch (Throwable t) { t.printStackTrace(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,4 +6,18 @@ plugins {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(project(":api"))
|
implementation(project(":api"))
|
||||||
|
implementation(libs.night.config.toml)
|
||||||
|
implementation(libs.asm)
|
||||||
|
|
||||||
|
testImplementation(libs.bundles.asm)
|
||||||
|
testImplementation(platform(libs.junit.bom))
|
||||||
|
testImplementation(libs.junit.jupiter)
|
||||||
|
testRuntimeOnly(libs.junit.platform.launcher)
|
||||||
|
// At runtime the game jar provides the driver.
|
||||||
|
testRuntimeOnly(libs.sqlite.jdbc)
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.test {
|
||||||
|
// The SQLite JDBC driver loads a native library; the server runs with the same flag.
|
||||||
|
jvmArgs("--enable-native-access=ALL-UNNAMED")
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package dev.overlord.zomboidforge.core;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.util.ResourceBundle;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@link System.Logger} that prints {@code [<name>] message} to standard output, which the
|
||||||
|
* Project Zomboid log captures. Levels below {@code INFO} are dropped; other levels than
|
||||||
|
* {@code INFO} are written before the message.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("CallToPrintStackTrace")
|
||||||
|
public final class ConsoleLogger implements System.Logger
|
||||||
|
{
|
||||||
|
private final String name;
|
||||||
|
|
||||||
|
public ConsoleLogger(String name) { this.name = name; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getName() { return this.name; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isLoggable(Level level) { return level != Level.OFF && level.getSeverity() >= Level.INFO.getSeverity(); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String message, @Nullable Throwable thrown)
|
||||||
|
{
|
||||||
|
if (!this.isLoggable(level)) return;
|
||||||
|
|
||||||
|
String prefix = level == Level.INFO ? "" : level.getName() + ": ";
|
||||||
|
System.out.println("[" + this.name + "] " + prefix + message);
|
||||||
|
|
||||||
|
if (thrown != null) thrown.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void log(
|
||||||
|
Level level,
|
||||||
|
@Nullable ResourceBundle bundle,
|
||||||
|
@Nullable String format,
|
||||||
|
@Nullable Object @Nullable ... parameters
|
||||||
|
) {
|
||||||
|
String message = format == null || parameters == null || parameters.length == 0
|
||||||
|
? format
|
||||||
|
: MessageFormat.format(format, parameters);
|
||||||
|
|
||||||
|
this.log(level, bundle, message, (Throwable) null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package dev.overlord.zomboidforge.core;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.Event;
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
import dev.overlord.zomboidforge.api.Mod;
|
||||||
|
import dev.overlord.zomboidforge.api.TickEvent;
|
||||||
|
import dev.overlord.zomboidforge.api.ZomboidForge;
|
||||||
|
import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||||
|
import dev.overlord.zomboidforge.core.config.ForgeSettings;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.GameClasses;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModDiscovery;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModLoader;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModResolver;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModServices;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModVerifier;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModVersion;
|
||||||
|
import dev.overlord.zomboidforge.core.runtime.EventBus;
|
||||||
|
import dev.overlord.zomboidforge.core.runtime.MainThreadQueue;
|
||||||
|
import dev.overlord.zomboidforge.core.runtime.ModThreads;
|
||||||
|
import dev.overlord.zomboidforge.core.storage.ModTables;
|
||||||
|
import dev.overlord.zomboidforge.core.storage.StorageDatabase;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ZomboidForge inside a running server: the lifecycle phase, the loaded mods, and their threads
|
||||||
|
* and events. The compat hooks call {@link #load}, {@link #started()}, {@link #tick()}, and
|
||||||
|
* {@link #stopping()}.
|
||||||
|
*/
|
||||||
|
public final class Forge
|
||||||
|
{
|
||||||
|
/** System property with the ZomboidForge directory, which contains {@code mods/}. */
|
||||||
|
public static final String DIRECTORY_PROPERTY = "zomboidforge.dir";
|
||||||
|
public static final String DEFAULT_DIRECTORY = "/forge";
|
||||||
|
|
||||||
|
private static final String MODS = "mods";
|
||||||
|
|
||||||
|
private final Lifecycle lifecycle = new Lifecycle();
|
||||||
|
private final System.Logger logger = new ConsoleLogger("ZomboidForge");
|
||||||
|
private final MainThreadQueue queue = new MainThreadQueue(ForgeSettings.DEFAULTS.mainThreadBudget());
|
||||||
|
private final EventBus events = new EventBus();
|
||||||
|
private final ModThreads threads = new ModThreads();
|
||||||
|
|
||||||
|
private final Path directory;
|
||||||
|
private final @Nullable ModVersion api;
|
||||||
|
|
||||||
|
private volatile List<ModLoader.LoadedMod> mods = List.of();
|
||||||
|
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
|
||||||
|
private volatile @Nullable StorageDatabase storage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param directory the ZomboidForge directory
|
||||||
|
* @param api the API version mods are checked against, or {@code null} to skip the
|
||||||
|
* check
|
||||||
|
*/
|
||||||
|
public Forge(Path directory, @Nullable ModVersion api)
|
||||||
|
{
|
||||||
|
this.directory = directory;
|
||||||
|
this.api = api;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Directory from {@value #DIRECTORY_PROPERTY} (default {@value #DEFAULT_DIRECTORY}); API
|
||||||
|
* version from {@link ZomboidForge#VERSION}. Builds without a release version ({@code dev},
|
||||||
|
* {@code 0.0.0-...}) skip the API check.
|
||||||
|
*/
|
||||||
|
public static Forge fromSystemProperties()
|
||||||
|
{
|
||||||
|
Path directory = Path.of(System.getProperty(Forge.DIRECTORY_PROPERTY, Forge.DEFAULT_DIRECTORY));
|
||||||
|
ModVersion api = ModVersion.tryParse(ZomboidForge.VERSION)
|
||||||
|
.filter(version -> version.major() != 0 || version.minor() != 0 || version.patch() != 0)
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
return new Forge(directory, api);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Lifecycle.Phase phase() { return this.lifecycle.phase(); }
|
||||||
|
|
||||||
|
public List<ModLoader.LoadedMod> mods() { return this.mods; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads {@code forge.toml}, then discovers, checks, and loads every mod in
|
||||||
|
* {@code <directory>/mods}. Called once on the main thread, which becomes the thread of
|
||||||
|
* {@code main()}. When a mod fails, the threads of the mods created so far are stopped.
|
||||||
|
*
|
||||||
|
* @param gameJar the Project Zomboid jar the server runs
|
||||||
|
* @param parent parent of the mods' class loaders; loads the game, the API, and ZomboidForge
|
||||||
|
* @param storageFile the world's {@code zomboidforge.db}; created when a mod first uses storage
|
||||||
|
* @throws ModLoadException listing every problem found
|
||||||
|
*/
|
||||||
|
public void load(GameVersion game, Path gameJar, ClassLoader parent, Path storageFile) throws ModLoadException
|
||||||
|
{
|
||||||
|
Path modsDirectory = this.directory.resolve(Forge.MODS);
|
||||||
|
|
||||||
|
try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)); }
|
||||||
|
catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "': " + e.getMessage(), e); }
|
||||||
|
|
||||||
|
this.queue.budget(this.settings.mainThreadBudget());
|
||||||
|
this.queue.bindToCurrentThread();
|
||||||
|
|
||||||
|
if (this.api == null) this.logger.log(System.Logger.Level.WARNING, "ZomboidForge " + ZomboidForge.VERSION + " is not a release; the API versions of mods are not checked.");
|
||||||
|
|
||||||
|
List<ModDiscovery.Candidate> candidates = Files.isDirectory(modsDirectory)
|
||||||
|
? ModDiscovery.discover(modsDirectory, this.logger)
|
||||||
|
: List.of();
|
||||||
|
|
||||||
|
List<String> disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).toList();
|
||||||
|
if (!disabled.isEmpty()) this.logger.log(System.Logger.Level.INFO, "Disabled in config.toml: " + String.join(", ", disabled) + ".");
|
||||||
|
|
||||||
|
List<ModDiscovery.Candidate> ordered = ModResolver.resolve(candidates, game, this.api);
|
||||||
|
List<String> installed = candidates.stream().map(ModDiscovery.Candidate::id).toList();
|
||||||
|
StorageDatabase storage = new StorageDatabase(storageFile, this::storageForbidden);
|
||||||
|
|
||||||
|
this.storage = storage;
|
||||||
|
|
||||||
|
try (GameClasses gameClasses = GameClasses.open(gameJar))
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
catch (IOException e)
|
||||||
|
{
|
||||||
|
this.stopMods(Duration.ZERO);
|
||||||
|
throw new ModLoadException("Cannot read the Project Zomboid jar '" + gameJar + "': " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
catch (StorageException e)
|
||||||
|
{
|
||||||
|
this.stopMods(Duration.ZERO);
|
||||||
|
throw new ModLoadException(e.getMessage() == null ? e.toString() : e.getMessage(), e);
|
||||||
|
}
|
||||||
|
catch (ModLoadException | RuntimeException e)
|
||||||
|
{
|
||||||
|
this.stopMods(Duration.ZERO);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.lifecycle.loaded();
|
||||||
|
|
||||||
|
this.logger.log(System.Logger.Level.INFO, this.mods.isEmpty()
|
||||||
|
? "No mods in '" + modsDirectory + "'."
|
||||||
|
: "Loaded " + this.mods.size() + " mod(s): " + this.mods.stream().map(mod -> mod.descriptor().id() + " " + mod.descriptor().version()).collect(Collectors.joining(", ")) + "."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls {@link Mod#onServerStarted()} of every mod in load order. 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) {
|
||||||
|
try { mod.mod().onServerStarted(); }
|
||||||
|
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Posts {@link TickEvent} (only when a listener exists), then runs queued main-thread tasks
|
||||||
|
* within the budget. Main thread, once per frame of the main loop.
|
||||||
|
*/
|
||||||
|
public void tick()
|
||||||
|
{
|
||||||
|
if (this.events.hasListeners(TickEvent.class)) this.events.post(new TickEvent(this.queue.tick() + 1));
|
||||||
|
|
||||||
|
this.queue.drain();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delivers {@code event} to the mods' listeners: main listeners run now on the calling
|
||||||
|
* thread, which must be the main thread; mod-thread listeners get a task on their mod's
|
||||||
|
* thread.
|
||||||
|
*/
|
||||||
|
public void post(Event event) { this.events.post(event); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pauses storage for a backup of the save folder (see {@link StorageDatabase#backupStarted()}).
|
||||||
|
* Called by the patched {@code ZipBackup.makeBackupFile}, on the thread that makes the backup.
|
||||||
|
*/
|
||||||
|
public void backupStarted()
|
||||||
|
{
|
||||||
|
StorageDatabase storage = this.storage;
|
||||||
|
if (storage == null) return;
|
||||||
|
|
||||||
|
String problem = storage.backupStarted();
|
||||||
|
if (problem != null) this.logger.log(System.Logger.Level.WARNING, problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resumes storage after {@link #backupStarted()}; same thread. */
|
||||||
|
public void backupFinished()
|
||||||
|
{
|
||||||
|
StorageDatabase storage = this.storage;
|
||||||
|
if (storage != null) storage.backupFinished();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Once: calls {@link Mod#onStopping()} of every mod in reverse load order, then stops the
|
||||||
|
* mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread,
|
||||||
|
* before the world is saved, so nothing a mod throws leaves this method.
|
||||||
|
*/
|
||||||
|
public void stopping()
|
||||||
|
{
|
||||||
|
if (!this.lifecycle.stopping()) return;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (ModLoader.LoadedMod mod : this.mods.reversed()) {
|
||||||
|
try { mod.mod().onStopping(); }
|
||||||
|
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", t); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
this.stopMods(this.settings.shutdownTimeout());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rejects further main-thread tasks and cancels the queued ones, stops event delivery, gives
|
||||||
|
* the mods' threads {@code timeout} to finish before they are interrupted, and closes the
|
||||||
|
* storage.
|
||||||
|
*/
|
||||||
|
private void stopMods(Duration timeout)
|
||||||
|
{
|
||||||
|
this.queue.close();
|
||||||
|
this.events.close();
|
||||||
|
this.threads.shutdown(timeout, this.logger);
|
||||||
|
|
||||||
|
StorageDatabase storage = this.storage;
|
||||||
|
if (storage == null) return;
|
||||||
|
|
||||||
|
try { storage.close(); }
|
||||||
|
catch (StorageException e) { this.logger.log(System.Logger.Level.ERROR, "Closing the storage failed.", e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The main thread may use storage only before the main loop runs. */
|
||||||
|
private boolean storageForbidden() { return this.queue.isMainThread() && this.lifecycle.phase() == Lifecycle.Phase.RUNNING; }
|
||||||
|
|
||||||
|
private ModServices services(String id, System.Logger logger)
|
||||||
|
{
|
||||||
|
ModThreads.ModExecutors executors = this.threads.create(id, logger);
|
||||||
|
|
||||||
|
StorageDatabase storage = Objects.requireNonNull(this.storage, "storage");
|
||||||
|
|
||||||
|
return new ModServices(
|
||||||
|
this.events.forMod(id, executors.modThread(), logger),
|
||||||
|
this.queue.forMod(id, logger),
|
||||||
|
executors.modThread(),
|
||||||
|
executors.async(),
|
||||||
|
new ModTables(id, storage, logger)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package dev.overlord.zomboidforge.core;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Phase of a server run, advanced by the hooks in the patched game code. {@link #loaded()} and
|
||||||
|
* {@link #started()} each happen once and in this order; {@link #stopping()} can follow any phase,
|
||||||
|
* because the JVM can be stopped at any time.
|
||||||
|
*/
|
||||||
|
public final class Lifecycle
|
||||||
|
{
|
||||||
|
public enum Phase
|
||||||
|
{
|
||||||
|
/** The JVM runs; mods are not loaded yet. */
|
||||||
|
BOOTING,
|
||||||
|
/** Mods are loaded; the game still loads the world and opens the network port. */
|
||||||
|
LOADED,
|
||||||
|
/** The main loop runs. */
|
||||||
|
RUNNING,
|
||||||
|
/** The shutdown started; the world is about to be saved. */
|
||||||
|
STOPPING
|
||||||
|
}
|
||||||
|
|
||||||
|
private final AtomicReference<Phase> phase = new AtomicReference<>(Phase.BOOTING);
|
||||||
|
|
||||||
|
public Phase phase() { return this.phase.get(); }
|
||||||
|
|
||||||
|
/** {@link Phase#BOOTING} to {@link Phase#LOADED}. */
|
||||||
|
public void loaded() { this.advance(Phase.BOOTING, Phase.LOADED); }
|
||||||
|
|
||||||
|
/** {@link Phase#LOADED} to {@link Phase#RUNNING}. */
|
||||||
|
public void started() { this.advance(Phase.LOADED, Phase.RUNNING); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Any phase to {@link Phase#STOPPING}.
|
||||||
|
*
|
||||||
|
* @return {@code false} when the phase already was {@link Phase#STOPPING}
|
||||||
|
*/
|
||||||
|
public boolean stopping() { return this.phase.getAndSet(Phase.STOPPING) != Phase.STOPPING; }
|
||||||
|
|
||||||
|
private void advance(Phase from, Phase to)
|
||||||
|
{
|
||||||
|
Phase current = this.phase.compareAndExchange(from, to);
|
||||||
|
|
||||||
|
if (current != from) throw new IllegalStateException("Cannot enter phase '" + to + "' from '" + current + "', only from '" + from + "'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.config;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Global settings from {@code <forge>/forge.toml}. Every key is optional:
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* [main_thread]
|
||||||
|
* budget_ms = 2 # time per tick for tasks that mods hand to the main thread
|
||||||
|
*
|
||||||
|
* [shutdown]
|
||||||
|
* timeout_s = 10 # how long mod threads get to finish when the server stops
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @param mainThreadBudget at least 1 ms
|
||||||
|
* @param shutdownTimeout 0 or more
|
||||||
|
*/
|
||||||
|
public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout)
|
||||||
|
{
|
||||||
|
public static final String FILE = "forge.toml";
|
||||||
|
public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10));
|
||||||
|
|
||||||
|
private record Document(Optional<MainThread> mainThread, Optional<Shutdown> shutdown) {}
|
||||||
|
private record MainThread(Optional<Long> budgetMs) {}
|
||||||
|
private record Shutdown(Optional<Long> timeoutS) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The settings in {@code file}, or {@link #DEFAULTS} when it does not exist.
|
||||||
|
*
|
||||||
|
* @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values
|
||||||
|
* of the wrong type or out of range
|
||||||
|
*/
|
||||||
|
public static ForgeSettings read(Path file)
|
||||||
|
{
|
||||||
|
if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS;
|
||||||
|
|
||||||
|
Map<String, Object> values;
|
||||||
|
|
||||||
|
try { values = TomlTree.parse(Files.readString(file)); }
|
||||||
|
catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); }
|
||||||
|
|
||||||
|
RecordBinder binder = new RecordBinder();
|
||||||
|
@Nullable Document document = binder.record(values, Document.class, "");
|
||||||
|
List<String> problems = new ArrayList<>(binder.problems());
|
||||||
|
|
||||||
|
for (String key : binder.unknownKeys()) problems.add("Unknown key '" + key + "'.");
|
||||||
|
|
||||||
|
if (document == null || !problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||||
|
|
||||||
|
long budget = document.mainThread().flatMap(MainThread::budgetMs).orElse(ForgeSettings.DEFAULTS.mainThreadBudget().toMillis());
|
||||||
|
long timeout = document.shutdown().flatMap(Shutdown::timeoutS).orElse(ForgeSettings.DEFAULTS.shutdownTimeout().toSeconds());
|
||||||
|
|
||||||
|
if (budget < 1) problems.add("'main_thread.budget_ms' must be at least 1, found " + budget + ".");
|
||||||
|
if (timeout < 0) problems.add("'shutdown.timeout_s' must not be negative, found " + timeout + ".");
|
||||||
|
|
||||||
|
if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems));
|
||||||
|
|
||||||
|
return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.config;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.ParameterizedType;
|
||||||
|
import java.lang.reflect.RecordComponent;
|
||||||
|
import java.lang.reflect.Type;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
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.
|
||||||
|
*/
|
||||||
|
public final class RecordBinder
|
||||||
|
{
|
||||||
|
private final List<String> problems = new ArrayList<>();
|
||||||
|
private final Set<String> unknownKeys = new TreeSet<>();
|
||||||
|
|
||||||
|
public List<String> problems() { return List.copyOf(this.problems); }
|
||||||
|
|
||||||
|
/** Dotted paths of keys that no record component reads, sorted. */
|
||||||
|
public List<String> unknownKeys() { return List.copyOf(this.unknownKeys); }
|
||||||
|
|
||||||
|
/** Record component name to TOML key: {@code maxBalance} to {@code max_balance}, {@code httpPort} to {@code http_port}. */
|
||||||
|
public static String key(String component)
|
||||||
|
{
|
||||||
|
StringBuilder key = new StringBuilder(component.length() + 4);
|
||||||
|
|
||||||
|
for (int i = 0; i < component.length(); i++)
|
||||||
|
{
|
||||||
|
char c = component.charAt(i);
|
||||||
|
boolean upper = Character.isUpperCase(c);
|
||||||
|
boolean afterLower = i > 0 && !Character.isUpperCase(component.charAt(i - 1));
|
||||||
|
boolean wordStart = i > 0 && i + 1 < component.length() && Character.isUpperCase(component.charAt(i - 1)) && Character.isLowerCase(component.charAt(i + 1));
|
||||||
|
|
||||||
|
if (upper && (afterLower || wordStart)) key.append('_');
|
||||||
|
key.append(Character.toLowerCase(c));
|
||||||
|
}
|
||||||
|
|
||||||
|
return key.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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();
|
||||||
|
@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());
|
||||||
|
keys.remove(key);
|
||||||
|
|
||||||
|
arguments[i] = this.value(table.get(key), components[i].getGenericType(), RecordBinder.join(path, key));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String key : keys) this.unknownKeys.add(RecordBinder.join(path, key));
|
||||||
|
|
||||||
|
// value() returns null only after recording a problem, so past this check no argument is null.
|
||||||
|
if (this.problems.size() > before) return null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Constructor<T> constructor = type.getDeclaredConstructor(Arrays.stream(components).map(RecordComponent::getType).toArray(Class<?>[]::new));
|
||||||
|
constructor.setAccessible(true);
|
||||||
|
|
||||||
|
return constructor.newInstance(arguments);
|
||||||
|
}
|
||||||
|
catch (InvocationTargetException e)
|
||||||
|
{
|
||||||
|
this.problems.add("'" + (path.isEmpty() ? "<root>" : path) + "': " + type.getSimpleName() + " rejected the values: " + e.getCause() + ".");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (ReflectiveOperationException e)
|
||||||
|
{
|
||||||
|
throw new IllegalStateException("Cannot create record '" + type.getName() + "'.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@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)
|
||||||
|
{
|
||||||
|
Class<?> type = RecordBinder.rawType(target);
|
||||||
|
|
||||||
|
if (type == Optional.class)
|
||||||
|
{
|
||||||
|
if (raw == null) return Optional.empty();
|
||||||
|
|
||||||
|
Object element = this.value(raw, RecordBinder.typeArgument(target, 0), path);
|
||||||
|
return element == null ? null : Optional.of(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (raw == null) return this.problem(path, "is missing");
|
||||||
|
|
||||||
|
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.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);
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "', which configuration values cannot have.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Object integer(Object raw, String path)
|
||||||
|
{
|
||||||
|
if (!(raw instanceof Long number)) return this.mistyped(path, "an integer", raw);
|
||||||
|
if (number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) return this.problem(path, "must be between " + Integer.MIN_VALUE + " and " + Integer.MAX_VALUE + ", found " + number);
|
||||||
|
|
||||||
|
return number.intValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Object constant(Object raw, Class<?> type, String path)
|
||||||
|
{
|
||||||
|
Object[] constants = type.getEnumConstants();
|
||||||
|
|
||||||
|
if (raw instanceof String name) {
|
||||||
|
for (Object constant : constants) {
|
||||||
|
if (((Enum<?>) constant).name().equalsIgnoreCase(name)) return constant;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String allowed = Arrays.stream(constants).map(constant -> "\"" + ((Enum<?>) constant).name().toLowerCase(Locale.ROOT) + "\"").collect(Collectors.joining(", "));
|
||||||
|
return this.mistyped(path, "one of " + allowed, raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Object list(Object raw, Type element, String path)
|
||||||
|
{
|
||||||
|
if (!(raw instanceof List<?> list)) return this.mistyped(path, "a list", raw);
|
||||||
|
|
||||||
|
List<Object> values = new ArrayList<>(list.size());
|
||||||
|
int before = this.problems.size();
|
||||||
|
|
||||||
|
for (int i = 0; i < list.size(); i++)
|
||||||
|
{
|
||||||
|
Object value = this.value(list.get(i), element, path + "[" + i + "]");
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
if (RecordBinder.typeArgument(target, 0) != String.class)
|
||||||
|
throw new IllegalArgumentException("'" + path + "' has the type '" + target.getTypeName() + "'; configuration maps need String keys.");
|
||||||
|
|
||||||
|
if (!(raw instanceof Map<?, ?> table)) return this.mistyped(path, "a table", raw);
|
||||||
|
|
||||||
|
Map<String, Object> values = new LinkedHashMap<>();
|
||||||
|
int before = this.problems.size();
|
||||||
|
|
||||||
|
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()));
|
||||||
|
if (value != null) values.put(entry.getKey(), value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.problems.size() > before ? null : Map.copyOf(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Object mistyped(String path, String expected, Object raw)
|
||||||
|
{
|
||||||
|
String found = raw instanceof Map<?, ?> ? "a table" : raw instanceof List<?> ? "a list" : raw instanceof String text ? "\"" + text + "\"" : String.valueOf(raw);
|
||||||
|
return this.problem(path, "must be " + expected + ", found " + found);
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Object problem(String path, String message)
|
||||||
|
{
|
||||||
|
this.problems.add("'" + path + "' " + message + ".");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Class<?> rawType(Type type)
|
||||||
|
{
|
||||||
|
return switch (type)
|
||||||
|
{
|
||||||
|
case Class<?> clazz -> clazz;
|
||||||
|
case ParameterizedType parameters -> (Class<?>) parameters.getRawType();
|
||||||
|
default -> throw new IllegalArgumentException("Configuration values cannot have the type '" + type.getTypeName() + "'.");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Type typeArgument(Type type, int index)
|
||||||
|
{
|
||||||
|
if (type instanceof ParameterizedType parameters) return parameters.getActualTypeArguments()[index];
|
||||||
|
|
||||||
|
throw new IllegalArgumentException("'" + type.getTypeName() + "' needs type arguments in configuration records.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String join(String path, String key) { return path.isEmpty() ? key : path + "." + key; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.config;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.ModConfig;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/** {@link ModConfig} over the merged {@link TomlTree} of a mod's {@code config.toml}. */
|
||||||
|
public final class TomlModConfig implements ModConfig
|
||||||
|
{
|
||||||
|
private final Map<String, Object> values;
|
||||||
|
private final System.Logger logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param values the settings without the {@code [forge]} table
|
||||||
|
* @param logger receives warnings about keys no record component reads
|
||||||
|
*/
|
||||||
|
public TomlModConfig(Map<String, Object> values, System.Logger logger)
|
||||||
|
{
|
||||||
|
this.values = Map.copyOf(values);
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends Record> T bind(Class<T> type)
|
||||||
|
{
|
||||||
|
RecordBinder binder = new RecordBinder();
|
||||||
|
T record = binder.record(this.values, type, "");
|
||||||
|
|
||||||
|
if (record == null || !binder.problems().isEmpty())
|
||||||
|
throw new IllegalStateException("config.toml does not match '" + type.getSimpleName() + "': " + String.join(" ", binder.problems()));
|
||||||
|
|
||||||
|
for (String key : binder.unknownKeys()) this.logger.log(System.Logger.Level.WARNING, "config.toml: unknown key '" + key + "'.");
|
||||||
|
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> Optional<T> get(String path, Class<T> type)
|
||||||
|
{
|
||||||
|
Object value = this.values;
|
||||||
|
|
||||||
|
for (String key : path.split("\\."))
|
||||||
|
{
|
||||||
|
if (!(value instanceof Map<?, ?> table)) return Optional.empty();
|
||||||
|
|
||||||
|
value = table.get(key);
|
||||||
|
if (value == null) return Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
RecordBinder binder = new RecordBinder();
|
||||||
|
Object converted = binder.value(value, type, path);
|
||||||
|
|
||||||
|
if (converted == null) throw new IllegalStateException("config.toml: " + String.join(" ", binder.problems()));
|
||||||
|
|
||||||
|
return Optional.of(type.cast(converted));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.config;
|
||||||
|
|
||||||
|
import com.electronwill.nightconfig.core.UnmodifiableConfig;
|
||||||
|
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||||
|
import com.electronwill.nightconfig.toml.TomlParser;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TOML documents as plain Java values: tables become {@code Map<String, Object>}, arrays
|
||||||
|
* {@code List<Object>}, integers {@code Long}, floats {@code Double}; strings and booleans stay
|
||||||
|
* as they are. Dates and times keep the types of the parser.
|
||||||
|
*/
|
||||||
|
public final class TomlTree
|
||||||
|
{
|
||||||
|
private TomlTree() {}
|
||||||
|
|
||||||
|
/** @throws IllegalArgumentException when {@code toml} is not valid TOML */
|
||||||
|
public static Map<String, Object> parse(String toml)
|
||||||
|
{
|
||||||
|
try { return TomlTree.table(new TomlParser().parse(toml)); }
|
||||||
|
catch (ParsingException e) { throw new IllegalArgumentException("Not valid TOML: " + e.getMessage(), e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code overrides} over {@code defaults}: tables are merged key by key, every other value of
|
||||||
|
* {@code overrides} replaces the default.
|
||||||
|
*/
|
||||||
|
public static Map<String, Object> merge(Map<String, Object> defaults, Map<String, Object> overrides)
|
||||||
|
{
|
||||||
|
Map<String, Object> merged = new LinkedHashMap<>(defaults);
|
||||||
|
|
||||||
|
for (Map.Entry<String, Object> entry : overrides.entrySet())
|
||||||
|
{
|
||||||
|
Object defaultValue = merged.get(entry.getKey());
|
||||||
|
|
||||||
|
if (defaultValue instanceof Map<?, ?> defaultTable && entry.getValue() instanceof Map<?, ?> table)
|
||||||
|
merged.put(entry.getKey(), TomlTree.merge(TomlTree.cast(defaultTable), TomlTree.cast(table)));
|
||||||
|
else
|
||||||
|
merged.put(entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, Object> table(UnmodifiableConfig config)
|
||||||
|
{
|
||||||
|
Map<String, Object> table = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
for (UnmodifiableConfig.Entry entry : config.entrySet()) table.put(entry.getKey(), TomlTree.value(entry.getRawValue()));
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object value(Object raw)
|
||||||
|
{
|
||||||
|
return switch (raw)
|
||||||
|
{
|
||||||
|
case UnmodifiableConfig config -> TomlTree.table(config);
|
||||||
|
case List<?> list -> TomlTree.list(list);
|
||||||
|
case Integer number -> number.longValue();
|
||||||
|
case Float number -> number.doubleValue();
|
||||||
|
default -> raw;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Object> list(List<?> raw)
|
||||||
|
{
|
||||||
|
List<Object> list = new ArrayList<>(raw.size());
|
||||||
|
|
||||||
|
for (Object element : raw) list.add(TomlTree.value(element));
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
static Map<String, Object> cast(Map<?, ?> table) { return (Map<String, Object>) table; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* TOML configuration: parsing into plain maps, merging over defaults, and binding to records.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.core.config;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.zip.ZipFile;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The classes of the Project Zomboid jar (game code and the libraries it bundles). The names
|
||||||
|
* stay available after {@link #close()}; the class files can be read until then.
|
||||||
|
*/
|
||||||
|
public final class GameClasses implements AutoCloseable
|
||||||
|
{
|
||||||
|
private static final String CLASS_SUFFIX = ".class";
|
||||||
|
private static final Pattern VERSIONED = Pattern.compile("META-INF/versions/\\d+/(.+)");
|
||||||
|
|
||||||
|
private final @Nullable JarFile file;
|
||||||
|
private final Set<String> classes;
|
||||||
|
private final Set<String> packages;
|
||||||
|
|
||||||
|
private GameClasses(@Nullable JarFile file, Set<String> classes, Set<String> packages)
|
||||||
|
{
|
||||||
|
this.file = file;
|
||||||
|
this.classes = Set.copyOf(classes);
|
||||||
|
this.packages = Set.copyOf(packages);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Indexes {@code jar}; multi-release entries count for their base name. */
|
||||||
|
public static GameClasses open(Path jar) throws IOException
|
||||||
|
{
|
||||||
|
JarFile file = new JarFile(jar.toFile(), true, ZipFile.OPEN_READ, Runtime.version());
|
||||||
|
Set<String> classes = new HashSet<>();
|
||||||
|
Set<String> packages = new HashSet<>();
|
||||||
|
|
||||||
|
for (JarEntry entry : file.stream().toList())
|
||||||
|
{
|
||||||
|
String name = entry.getName();
|
||||||
|
Matcher versioned = GameClasses.VERSIONED.matcher(name);
|
||||||
|
|
||||||
|
if (versioned.matches()) name = versioned.group(1);
|
||||||
|
if (!name.endsWith(GameClasses.CLASS_SUFFIX) || name.startsWith("META-INF/")) continue;
|
||||||
|
|
||||||
|
String internalName = name.substring(0, name.length() - GameClasses.CLASS_SUFFIX.length());
|
||||||
|
classes.add(internalName);
|
||||||
|
packages.add(GameClasses.packageOf(internalName));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new GameClasses(file, classes, packages);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** No game classes, for checking a mod that declares no {@code game} versions without a game jar. */
|
||||||
|
public static GameClasses none() { return new GameClasses(null, Set.of(), Set.of()); }
|
||||||
|
|
||||||
|
/** Whether the jar contains the class with this internal name, e.g. {@code zombie/core/Core}. */
|
||||||
|
public boolean contains(String internalName) { return this.classes.contains(internalName); }
|
||||||
|
|
||||||
|
/** Whether the jar contains classes in the package of this internal class name. */
|
||||||
|
public boolean containsPackageOf(String internalName) { return this.packages.contains(GameClasses.packageOf(internalName)); }
|
||||||
|
|
||||||
|
/** The class file for the running Java version, or {@code null} when the jar has none. */
|
||||||
|
byte @Nullable [] read(String internalName) throws IOException
|
||||||
|
{
|
||||||
|
JarFile file = this.file;
|
||||||
|
if (file == null) return null;
|
||||||
|
|
||||||
|
JarEntry entry = file.getJarEntry(internalName + GameClasses.CLASS_SUFFIX);
|
||||||
|
if (entry == null) return null;
|
||||||
|
|
||||||
|
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException
|
||||||
|
{
|
||||||
|
JarFile file = this.file;
|
||||||
|
if (file != null) file.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
static String packageOf(String internalName)
|
||||||
|
{
|
||||||
|
int slash = internalName.lastIndexOf('/');
|
||||||
|
return slash < 0 ? "" : internalName.substring(0, slash);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** Packages of the modules in the boot layer (the JDK), with the class loader of each. */
|
||||||
|
final class JdkPackages
|
||||||
|
{
|
||||||
|
private static final Map<String, ClassLoader> LOADERS = JdkPackages.loaders();
|
||||||
|
|
||||||
|
private JdkPackages() {}
|
||||||
|
|
||||||
|
/** The loader for a class of the JDK package {@code dottedPackage}, or {@code null} for other packages. */
|
||||||
|
static @Nullable ClassLoader loader(String dottedPackage) { return JdkPackages.LOADERS.get(dottedPackage); }
|
||||||
|
|
||||||
|
/** Whether the class with this internal name, e.g. {@code java/util/List}, is in a JDK package. */
|
||||||
|
static boolean contains(String internalName) { return JdkPackages.LOADERS.containsKey(GameClasses.packageOf(internalName).replace('/', '.')); }
|
||||||
|
|
||||||
|
private static Map<String, ClassLoader> loaders()
|
||||||
|
{
|
||||||
|
Map<String, ClassLoader> loaders = new HashMap<>();
|
||||||
|
|
||||||
|
for (Module module : ModuleLayer.boot().modules())
|
||||||
|
{
|
||||||
|
// Modules of the boot loader report null; the platform loader delegates to it.
|
||||||
|
ClassLoader loader = module.getClassLoader() == null ? ClassLoader.getPlatformClassLoader() : module.getClassLoader();
|
||||||
|
|
||||||
|
for (String name : module.getPackages()) loaders.put(name, loader);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Map.copyOf(loaders);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.URLClassLoader;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class loader of one mod, over its jar and its {@code lib/} jars. Lookup order:
|
||||||
|
*
|
||||||
|
* <ol>
|
||||||
|
* <li>JDK classes, from the loader of their module;</li>
|
||||||
|
* <li>the ZomboidForge API ({@code dev.overlord.zomboidforge.api}, without {@code .internal}),
|
||||||
|
* from the parent;</li>
|
||||||
|
* <li>the mod's own jar and libraries;</li>
|
||||||
|
* <li>the own jars (not the libraries) of the mod's declared dependencies;</li>
|
||||||
|
* <li>classes of the Project Zomboid jar, from the parent, only for mods that declare
|
||||||
|
* {@code game} versions.</li>
|
||||||
|
* </ol>
|
||||||
|
*
|
||||||
|
* Everything else on the parent's class path, such as ZomboidForge's own classes and libraries,
|
||||||
|
* is not visible. A mod's own copy of a library that the game also bundles takes precedence.
|
||||||
|
*
|
||||||
|
* <p>The lookup order prevents accidental linkage only. It is not a security boundary: mod code
|
||||||
|
* can still reach other classes through reflection or {@link ClassLoader#getSystemClassLoader()}.
|
||||||
|
*/
|
||||||
|
final class ModClassLoader extends URLClassLoader
|
||||||
|
{
|
||||||
|
private static final String API = "dev.overlord.zomboidforge.api.";
|
||||||
|
private static final String API_INTERNAL = "dev.overlord.zomboidforge.api.internal.";
|
||||||
|
|
||||||
|
static { ClassLoader.registerAsParallelCapable(); }
|
||||||
|
|
||||||
|
private final String id;
|
||||||
|
private final Set<String> ownClasses;
|
||||||
|
private final List<ModClassLoader> dependencies;
|
||||||
|
private final @Nullable GameClasses game;
|
||||||
|
|
||||||
|
/** @param game the game's classes, or {@code null} when the mod declares no {@code game} versions */
|
||||||
|
ModClassLoader(String id, Path jar, List<Path> libraries, ClassLoader parent, List<ModClassLoader> dependencies, @Nullable GameClasses game)
|
||||||
|
{
|
||||||
|
super("mod:" + id, ModClassLoader.urls(jar, libraries), parent);
|
||||||
|
|
||||||
|
this.id = id;
|
||||||
|
this.ownClasses = ModClassLoader.classNames(jar);
|
||||||
|
this.dependencies = List.copyOf(dependencies);
|
||||||
|
this.game = game;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a class with this binary name is part of the mod API. */
|
||||||
|
static boolean isApi(String name) { return name.startsWith(ModClassLoader.API) && !name.startsWith(ModClassLoader.API_INTERNAL); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException
|
||||||
|
{
|
||||||
|
synchronized (this.getClassLoadingLock(name))
|
||||||
|
{
|
||||||
|
Class<?> type = this.findLoadedClass(name);
|
||||||
|
if (type == null) type = this.lookUp(name);
|
||||||
|
if (resolve) this.resolveClass(type);
|
||||||
|
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resources of the mod's own jars first, then the parent's. */
|
||||||
|
@Override
|
||||||
|
public @Nullable URL getResource(String name)
|
||||||
|
{
|
||||||
|
URL own = this.findResource(name);
|
||||||
|
return own != null ? own : super.getResource(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Class<?> lookUp(String name) throws ClassNotFoundException
|
||||||
|
{
|
||||||
|
int dot = name.lastIndexOf('.');
|
||||||
|
ClassLoader jdk = JdkPackages.loader(dot < 0 ? "" : name.substring(0, dot));
|
||||||
|
|
||||||
|
if (jdk != null) return jdk.loadClass(name);
|
||||||
|
if (ModClassLoader.isApi(name)) return this.getParent().loadClass(name);
|
||||||
|
|
||||||
|
try { return this.findClass(name); }
|
||||||
|
catch (ClassNotFoundException e) { /* not in the mod's own jars */ }
|
||||||
|
|
||||||
|
for (ModClassLoader dependency : this.dependencies) {
|
||||||
|
if (dependency.ownClasses.contains(name)) return dependency.loadClass(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.game != null && this.game.contains(name.replace('.', '/'))) return this.getParent().loadClass(name);
|
||||||
|
|
||||||
|
throw new ClassNotFoundException(name + " (not visible to mod '" + this.id + "')");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static URL[] urls(Path jar, List<Path> libraries)
|
||||||
|
{
|
||||||
|
URL[] urls = new URL[libraries.size() + 1];
|
||||||
|
urls[0] = ModClassLoader.url(jar);
|
||||||
|
|
||||||
|
for (int i = 0; i < libraries.size(); i++) urls[i + 1] = ModClassLoader.url(libraries.get(i));
|
||||||
|
|
||||||
|
return urls;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static URL url(Path path)
|
||||||
|
{
|
||||||
|
try { return path.toUri().toURL(); }
|
||||||
|
catch (MalformedURLException e) { throw new IllegalArgumentException("'" + path + "' has no URL.", e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Binary names of the classes in {@code jar}, e.g. {@code com.example.Mod$Inner}. */
|
||||||
|
private static Set<String> classNames(Path jar)
|
||||||
|
{
|
||||||
|
try (JarFile file = new JarFile(jar.toFile()))
|
||||||
|
{
|
||||||
|
return file.stream()
|
||||||
|
.map(JarEntry::getName)
|
||||||
|
.filter(name -> name.endsWith(".class") && !name.startsWith("META-INF/"))
|
||||||
|
.map(name -> name.substring(0, name.length() - ".class".length()).replace('/', '.'))
|
||||||
|
.collect(Collectors.toUnmodifiableSet());
|
||||||
|
}
|
||||||
|
catch (IOException e) { throw new UncheckedIOException("Cannot read '" + jar + "'.", e); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
|
||||||
|
import com.electronwill.nightconfig.core.UnmodifiableConfig;
|
||||||
|
import com.electronwill.nightconfig.core.io.ParsingException;
|
||||||
|
import com.electronwill.nightconfig.toml.TomlParser;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contents of {@code META-INF/zomboidforge/mod.toml} in a mod's jar, written by the mod's author.
|
||||||
|
*
|
||||||
|
* @param game version prefixes of Project Zomboid the mod supports; empty when the mod
|
||||||
|
* uses no game classes
|
||||||
|
* @param previousIds earlier ids of the mod, whose storage moves to {@code id}
|
||||||
|
* @param dependencies mod id to minimum version
|
||||||
|
*/
|
||||||
|
public record ModDescriptor(
|
||||||
|
String id,
|
||||||
|
String name,
|
||||||
|
ModVersion version,
|
||||||
|
String entrypoint,
|
||||||
|
ModVersion api,
|
||||||
|
List<String> game,
|
||||||
|
List<String> previousIds,
|
||||||
|
Map<String, ModVersion> dependencies
|
||||||
|
)
|
||||||
|
{
|
||||||
|
/** Location of the descriptor inside a mod's jar. */
|
||||||
|
public static final String PATH = "META-INF/zomboidforge/mod.toml";
|
||||||
|
|
||||||
|
/** No {@code __} and no trailing {@code _}: storage tables are named {@code <id>__<table>}. */
|
||||||
|
private static final Pattern ID = Pattern.compile("[a-z][a-z0-9]*(_[a-z0-9]+)*");
|
||||||
|
private static final int ID_MAX_LENGTH = 32;
|
||||||
|
private static final Pattern CLASS_NAME = Pattern.compile("[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
|
||||||
|
|
||||||
|
private static final Set<String> RESERVED_IDS = Set.of("forge", "zomboidforge", "core", "api", "game");
|
||||||
|
private static final Set<String> KEYS = Set.of("id", "name", "version", "entrypoint", "api", "game", "previous_ids", "dependencies");
|
||||||
|
|
||||||
|
public ModDescriptor
|
||||||
|
{
|
||||||
|
game = List.copyOf(game);
|
||||||
|
previousIds = List.copyOf(previousIds);
|
||||||
|
dependencies = Map.copyOf(dependencies);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether {@code id} is a valid mod id that is not reserved. */
|
||||||
|
public static boolean isValidId(String id)
|
||||||
|
{
|
||||||
|
return id.length() <= ModDescriptor.ID_MAX_LENGTH
|
||||||
|
&& ModDescriptor.ID.matcher(id).matches()
|
||||||
|
&& !ModDescriptor.RESERVED_IDS.contains(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @throws ModLoadException listing every problem of the descriptor */
|
||||||
|
public static ModDescriptor parse(String toml) throws ModLoadException
|
||||||
|
{
|
||||||
|
UnmodifiableConfig config;
|
||||||
|
|
||||||
|
try { config = new TomlParser().parse(toml); }
|
||||||
|
catch (ParsingException e) { throw new ModLoadException("Not valid TOML: " + e.getMessage(), e); }
|
||||||
|
|
||||||
|
Reader reader = new Reader(config);
|
||||||
|
|
||||||
|
for (UnmodifiableConfig.Entry entry : config.entrySet()) {
|
||||||
|
if (!ModDescriptor.KEYS.contains(entry.getKey())) reader.problems.add("Unknown key '" + entry.getKey() + "'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
String id = reader.string("id", true);
|
||||||
|
String name = reader.string("name", false);
|
||||||
|
ModVersion version = reader.version("version");
|
||||||
|
String entrypoint = reader.string("entrypoint", true);
|
||||||
|
ModVersion api = reader.version("api");
|
||||||
|
List<String> game = reader.stringList("game");
|
||||||
|
List<String> previousIds = reader.stringList("previous_ids");
|
||||||
|
|
||||||
|
Map<String, ModVersion> dependencies = reader.dependencies();
|
||||||
|
|
||||||
|
if (id != null && !ModDescriptor.isValidId(id)) reader.problems.add("'id' = '" + id + "' is not a valid mod id (" + ModDescriptor.ID.pattern() + ", at most " + ModDescriptor.ID_MAX_LENGTH + " characters, not one of " + ModDescriptor.RESERVED_IDS + ").");
|
||||||
|
if (entrypoint != null && !ModDescriptor.CLASS_NAME.matcher(entrypoint).matches()) reader.problems.add("'entrypoint' = '" + entrypoint + "' is not a class name.");
|
||||||
|
|
||||||
|
if (reader.has("game") && game.isEmpty()) reader.problems.add("'game' is empty; leave it out when the mod uses no game classes.");
|
||||||
|
for (String prefix : game) {
|
||||||
|
if (!GameVersion.isPrefix(prefix)) reader.problems.add("'game' contains '" + prefix + "', which is not a version prefix such as '42' or '42.21'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String previousId : previousIds) {
|
||||||
|
if (!ModDescriptor.isValidId(previousId) || previousId.equals(id)) reader.problems.add("'previous_ids' contains '" + previousId + "', which is not a valid earlier mod id.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (id != null && dependencies.containsKey(id)) reader.problems.add("'dependencies' contains the mod itself.");
|
||||||
|
|
||||||
|
if (!reader.problems.isEmpty() || id == null || version == null || entrypoint == null || api == null)
|
||||||
|
throw new ModLoadException(reader.problems);
|
||||||
|
|
||||||
|
return new ModDescriptor(id, name == null ? id : name, version, entrypoint, api, game, previousIds, dependencies);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reads typed values and collects a problem for each missing or mistyped one. */
|
||||||
|
private static final class Reader
|
||||||
|
{
|
||||||
|
private final UnmodifiableConfig config;
|
||||||
|
private final List<String> problems = new ArrayList<>();
|
||||||
|
|
||||||
|
private Reader(UnmodifiableConfig config) { this.config = config; }
|
||||||
|
|
||||||
|
private boolean has(String key) { return this.config.contains(key); }
|
||||||
|
|
||||||
|
private @Nullable String string(String key, boolean required)
|
||||||
|
{
|
||||||
|
Object value = this.config.get(key);
|
||||||
|
|
||||||
|
if (value == null) {
|
||||||
|
if (required) this.problems.add("'" + key + "' is missing.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value instanceof String text && !text.isBlank()) return text.trim();
|
||||||
|
|
||||||
|
this.problems.add("'" + key + "' must be a non-empty string.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable ModVersion version(String key)
|
||||||
|
{
|
||||||
|
String text = this.string(key, true);
|
||||||
|
if (text == null) return null;
|
||||||
|
|
||||||
|
ModVersion version = ModVersion.tryParse(text).orElse(null);
|
||||||
|
if (version == null) this.problems.add("'" + key + "' = '" + text + "' is not a version such as '1.2.0'.");
|
||||||
|
|
||||||
|
return version;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> stringList(String key)
|
||||||
|
{
|
||||||
|
Object value = this.config.get(key);
|
||||||
|
if (value == null) return List.of();
|
||||||
|
|
||||||
|
List<String> strings = new ArrayList<>();
|
||||||
|
|
||||||
|
if (value instanceof List<?> list)
|
||||||
|
{
|
||||||
|
for (Object element : list) {
|
||||||
|
if (element instanceof String text) strings.add(text.trim());
|
||||||
|
else this.problems.add("'" + key + "' must contain only strings.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else this.problems.add("'" + key + "' must be a list of strings, e.g. [\"a\", \"b\"].");
|
||||||
|
|
||||||
|
return strings;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, ModVersion> dependencies()
|
||||||
|
{
|
||||||
|
Object value = this.config.get("dependencies");
|
||||||
|
if (value == null) return Map.of();
|
||||||
|
|
||||||
|
if (!(value instanceof UnmodifiableConfig table)) {
|
||||||
|
this.problems.add("'dependencies' must be a table of mod id = minimum version.");
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, ModVersion> dependencies = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
for (UnmodifiableConfig.Entry entry : table.entrySet())
|
||||||
|
{
|
||||||
|
String dependency = entry.getKey();
|
||||||
|
ModVersion minimum = entry.getRawValue() instanceof String text ? ModVersion.tryParse(text).orElse(null) : null;
|
||||||
|
|
||||||
|
if (!ModDescriptor.isValidId(dependency)) this.problems.add("'dependencies' contains '" + dependency + "', which is not a valid mod id.");
|
||||||
|
if (minimum == null) this.problems.add("'dependencies." + dependency + "' must be a version string such as \"1.2\".");
|
||||||
|
else dependencies.put(dependency, minimum);
|
||||||
|
}
|
||||||
|
|
||||||
|
return dependencies;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.core.config.TomlTree;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
import java.util.zip.ZipEntry;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the mods in {@code <forge>/mods}. Every mod is a folder named after its id:
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* mods/<id>/
|
||||||
|
* <id>.jar the mod, with META-INF/zomboidforge/mod.toml
|
||||||
|
* lib/*.jar libraries of the mod (optional)
|
||||||
|
* config.toml settings of the mod (optional)
|
||||||
|
* </pre>
|
||||||
|
*/
|
||||||
|
public final class ModDiscovery
|
||||||
|
{
|
||||||
|
/** Location of the default settings inside a mod's jar. */
|
||||||
|
public static final String DEFAULT_CONFIG = "META-INF/zomboidforge/config.toml";
|
||||||
|
public static final String CONFIG = "config.toml";
|
||||||
|
|
||||||
|
private static final String JAR_SUFFIX = ".jar";
|
||||||
|
private static final String LIBRARIES = "lib";
|
||||||
|
private static final String FORGE_TABLE = "forge";
|
||||||
|
private static final String ENABLED = "enabled";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A mod folder whose descriptor and settings were read.
|
||||||
|
*
|
||||||
|
* @param enabled {@code [forge] enabled} from the settings; {@code true} when missing
|
||||||
|
* @param config the settings over the defaults from the jar, without the {@code [forge]} table
|
||||||
|
*/
|
||||||
|
public record Candidate(Path directory, Path jar, List<Path> libraries, ModDescriptor descriptor, boolean enabled, Map<String, Object> config)
|
||||||
|
{
|
||||||
|
public Candidate
|
||||||
|
{
|
||||||
|
libraries = List.copyOf(libraries);
|
||||||
|
config = Map.copyOf(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String id() { return this.descriptor.id(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private record JarContents(String descriptor, byte @Nullable [] defaultConfig) {}
|
||||||
|
|
||||||
|
private ModDiscovery() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads every mod folder in {@code modsDirectory}, sorted by folder name. Writes the default
|
||||||
|
* settings of a mod to {@code config.toml} when the folder has none and is writable.
|
||||||
|
*
|
||||||
|
* @param logger receives notes about written or unwritable default settings
|
||||||
|
* @throws ModLoadException listing the problems of every folder
|
||||||
|
*/
|
||||||
|
public static List<Candidate> discover(Path modsDirectory, System.Logger logger) throws ModLoadException
|
||||||
|
{
|
||||||
|
List<Candidate> candidates = new ArrayList<>();
|
||||||
|
List<String> problems = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Path entry : ModDiscovery.sortedEntries(modsDirectory))
|
||||||
|
{
|
||||||
|
String name = entry.getFileName().toString();
|
||||||
|
|
||||||
|
if (name.startsWith(".")) continue;
|
||||||
|
|
||||||
|
if (!Files.isDirectory(entry)) {
|
||||||
|
problems.add("'" + name + "': not a folder; every mod is a folder 'mods/<id>/' with '<id>.jar' inside.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try { candidates.add(ModDiscovery.read(entry, logger)); }
|
||||||
|
catch (ModLoadException e) { e.problems().forEach(problem -> problems.add("'" + name + "': " + problem)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||||
|
|
||||||
|
return candidates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Candidate read(Path directory, System.Logger logger) throws ModLoadException
|
||||||
|
{
|
||||||
|
String name = directory.getFileName().toString();
|
||||||
|
Path jar = directory.resolve(name + ModDiscovery.JAR_SUFFIX);
|
||||||
|
List<String> problems = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Path entry : ModDiscovery.sortedEntries(directory)) {
|
||||||
|
if (ModDiscovery.isJar(entry) && !entry.equals(jar)) problems.add("'" + entry.getFileName() + "' is not '" + jar.getFileName() + "'; the folder may contain only the mod's own jar (libraries go into 'lib/').");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Files.isRegularFile(jar)) problems.add("'" + jar.getFileName() + "' is missing.");
|
||||||
|
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||||
|
|
||||||
|
JarContents contents = ModDiscovery.contents(jar);
|
||||||
|
ModDescriptor descriptor = ModDiscovery.descriptor(contents.descriptor());
|
||||||
|
if (!descriptor.id().equals(name)) throw new ModLoadException(List.of("The folder is named '" + name + "', but 'mod.toml' declares the id '" + descriptor.id() + "'."));
|
||||||
|
|
||||||
|
Path libraryDirectory = directory.resolve(ModDiscovery.LIBRARIES);
|
||||||
|
List<Path> libraries = Files.isDirectory(libraryDirectory)
|
||||||
|
? ModDiscovery.sortedEntries(libraryDirectory).stream().filter(ModDiscovery::isJar).toList()
|
||||||
|
: List.of();
|
||||||
|
|
||||||
|
Map<String, Object> config = ModDiscovery.config(directory, contents.defaultConfig(), logger, problems);
|
||||||
|
boolean enabled = ModDiscovery.enabled(config.remove(ModDiscovery.FORGE_TABLE), problems);
|
||||||
|
|
||||||
|
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||||
|
|
||||||
|
return new Candidate(directory, jar, libraries, descriptor, enabled, config);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The folder's {@code config.toml} over the jar's defaults, as a mutable map. */
|
||||||
|
private static Map<String, Object> config(Path directory, byte @Nullable [] defaultConfig, System.Logger logger, List<String> problems)
|
||||||
|
{
|
||||||
|
Path file = directory.resolve(ModDiscovery.CONFIG);
|
||||||
|
Map<String, Object> defaults = Map.of();
|
||||||
|
Map<String, Object> settings = Map.of();
|
||||||
|
|
||||||
|
if (defaultConfig != null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
defaults = TomlTree.parse(new String(defaultConfig, StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
catch (IllegalArgumentException e)
|
||||||
|
{
|
||||||
|
// Invalid defaults are reported and never copied to the folder.
|
||||||
|
problems.add("'" + ModDiscovery.DEFAULT_CONFIG + "' in the jar: " + e.getMessage());
|
||||||
|
return new LinkedHashMap<>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Files.isRegularFile(file))
|
||||||
|
{
|
||||||
|
try { settings = TomlTree.parse(Files.readString(file)); }
|
||||||
|
catch (IOException e) { problems.add("Cannot read '" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
|
||||||
|
catch (IllegalArgumentException e) { problems.add("'" + ModDiscovery.CONFIG + "': " + e.getMessage()); }
|
||||||
|
}
|
||||||
|
else if (defaultConfig != null)
|
||||||
|
{
|
||||||
|
String id = directory.getFileName().toString();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Files.write(file, defaultConfig, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
|
||||||
|
logger.log(System.Logger.Level.INFO, "'" + id + "': wrote the default settings to '" + file + "'.");
|
||||||
|
}
|
||||||
|
catch (IOException | UnsupportedOperationException e)
|
||||||
|
{
|
||||||
|
logger.log(System.Logger.Level.INFO, "'" + id + "': cannot write the default settings to '" + file + "' (" + e + "); using them without a file.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return TomlTree.merge(defaults, settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code [forge] enabled}; {@code true} without a {@code [forge]} table. */
|
||||||
|
private static boolean enabled(@Nullable Object forge, List<String> problems)
|
||||||
|
{
|
||||||
|
if (forge == null) return true;
|
||||||
|
|
||||||
|
if (!(forge instanceof Map<?, ?> table)) {
|
||||||
|
problems.add("'" + ModDiscovery.CONFIG + "': 'forge' must be a table ([forge]).");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean enabled = true;
|
||||||
|
|
||||||
|
for (Map.Entry<?, ?> entry : table.entrySet())
|
||||||
|
{
|
||||||
|
if (!ModDiscovery.ENABLED.equals(entry.getKey()))
|
||||||
|
problems.add("'" + ModDiscovery.CONFIG + "': unknown key 'forge." + entry.getKey() + "'; [forge] only has 'enabled'.");
|
||||||
|
else if (entry.getValue() instanceof Boolean value)
|
||||||
|
enabled = value;
|
||||||
|
else
|
||||||
|
problems.add("'" + ModDiscovery.CONFIG + "': 'forge.enabled' must be true or false.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JarContents contents(Path jar) throws ModLoadException
|
||||||
|
{
|
||||||
|
try (JarFile file = new JarFile(jar.toFile()))
|
||||||
|
{
|
||||||
|
byte[] descriptor = ModDiscovery.entry(file, ModDescriptor.PATH);
|
||||||
|
if (descriptor == null) throw new ModLoadException(List.of("'" + jar.getFileName() + "' contains no '" + ModDescriptor.PATH + "'."));
|
||||||
|
|
||||||
|
return new JarContents(new String(descriptor, StandardCharsets.UTF_8), ModDiscovery.entry(file, ModDiscovery.DEFAULT_CONFIG));
|
||||||
|
}
|
||||||
|
catch (IOException e) { throw new ModLoadException("Cannot read '" + jar.getFileName() + "': " + e.getMessage(), e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte @Nullable [] entry(JarFile file, String name) throws IOException
|
||||||
|
{
|
||||||
|
ZipEntry entry = file.getEntry(name);
|
||||||
|
if (entry == null) return null;
|
||||||
|
|
||||||
|
try (InputStream in = file.getInputStream(entry)) { return in.readAllBytes(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ModDescriptor descriptor(String toml) throws ModLoadException
|
||||||
|
{
|
||||||
|
try { return ModDescriptor.parse(toml); }
|
||||||
|
catch (ModLoadException e) { throw new ModLoadException(e.problems().stream().map(problem -> "mod.toml: " + problem).toList()); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isJar(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(ModDiscovery.JAR_SUFFIX); }
|
||||||
|
|
||||||
|
private static List<Path> sortedEntries(Path directory) throws ModLoadException
|
||||||
|
{
|
||||||
|
try (Stream<Path> entries = Files.list(directory)) { return entries.sorted().toList(); }
|
||||||
|
catch (IOException e) { throw new ModLoadException("Cannot list '" + directory + "': " + e.getMessage(), e); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import java.io.Serial;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/** The mods cannot be loaded; {@link #problems()} lists every problem found, one line each. */
|
||||||
|
public final class ModLoadException extends Exception
|
||||||
|
{
|
||||||
|
@Serial
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
/** Not serialized; the exception is only used inside the server process. */
|
||||||
|
private final transient List<String> problems;
|
||||||
|
|
||||||
|
public ModLoadException(List<String> problems)
|
||||||
|
{
|
||||||
|
super(String.join("\n", problems));
|
||||||
|
|
||||||
|
if (problems.isEmpty()) throw new IllegalArgumentException("A ModLoadException needs at least one problem.");
|
||||||
|
|
||||||
|
this.problems = List.copyOf(problems);
|
||||||
|
}
|
||||||
|
|
||||||
|
public ModLoadException(String problem, Throwable cause)
|
||||||
|
{
|
||||||
|
super(problem, cause);
|
||||||
|
|
||||||
|
this.problems = List.of(problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> problems() { return this.problems; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.AsyncExecutor;
|
||||||
|
import dev.overlord.zomboidforge.api.Events;
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
import dev.overlord.zomboidforge.api.MainThread;
|
||||||
|
import dev.overlord.zomboidforge.api.Mod;
|
||||||
|
import dev.overlord.zomboidforge.api.ModConfig;
|
||||||
|
import dev.overlord.zomboidforge.api.ModContext;
|
||||||
|
import dev.overlord.zomboidforge.api.ModThread;
|
||||||
|
import dev.overlord.zomboidforge.api.internal.ModBinding;
|
||||||
|
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||||
|
import dev.overlord.zomboidforge.core.ConsoleLogger;
|
||||||
|
import dev.overlord.zomboidforge.core.config.TomlModConfig;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.lang.reflect.Constructor;
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
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.
|
||||||
|
*/
|
||||||
|
public final class ModLoader
|
||||||
|
{
|
||||||
|
/** A mod whose entry point was created and whose {@link Mod#onLoad()} returned. */
|
||||||
|
public record LoadedMod(ModDescriptor descriptor, Path directory, ClassLoader classLoader, Mod mod) {}
|
||||||
|
|
||||||
|
private record Context(
|
||||||
|
String id,
|
||||||
|
String version,
|
||||||
|
GameVersion gameVersion,
|
||||||
|
System.Logger logger,
|
||||||
|
Path directory,
|
||||||
|
ModConfig config,
|
||||||
|
Events events,
|
||||||
|
MainThread main,
|
||||||
|
ModThread modThread,
|
||||||
|
AsyncExecutor async,
|
||||||
|
ModStorage storage
|
||||||
|
) implements ModContext {}
|
||||||
|
|
||||||
|
private ModLoader() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ordered mods in load order, as returned by {@link ModResolver#resolve} and checked
|
||||||
|
* by {@link ModVerifier#verify}
|
||||||
|
* @param parent parent of every mod's class loader
|
||||||
|
* @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
|
||||||
|
* @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
|
||||||
|
{
|
||||||
|
Map<String, ModClassLoader> loaders = new HashMap<>();
|
||||||
|
List<LoadedMod> loaded = new ArrayList<>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
for (ModDiscovery.Candidate candidate : ordered)
|
||||||
|
{
|
||||||
|
ModDescriptor descriptor = candidate.descriptor();
|
||||||
|
|
||||||
|
List<ModClassLoader> dependencies = descriptor.dependencies().keySet().stream()
|
||||||
|
.sorted()
|
||||||
|
.map(dependency -> Objects.requireNonNull(loaders.get(dependency), "'" + dependency + "' is not loaded before '" + descriptor.id() + "'."))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
@Nullable GameClasses visible = descriptor.game().isEmpty() ? null : gameClasses;
|
||||||
|
ModClassLoader loader = new ModClassLoader(descriptor.id(), candidate.jar(), candidate.libraries(), parent, dependencies, visible);
|
||||||
|
loaders.put(descriptor.id(), loader);
|
||||||
|
|
||||||
|
System.Logger logger = new ConsoleLogger("ZomboidForge/" + descriptor.id());
|
||||||
|
ModServices provided = services.create(descriptor.id(), logger);
|
||||||
|
Context context = new Context(
|
||||||
|
descriptor.id(),
|
||||||
|
descriptor.version().toString(),
|
||||||
|
game,
|
||||||
|
logger,
|
||||||
|
candidate.directory(),
|
||||||
|
new TomlModConfig(candidate.config(), logger),
|
||||||
|
provided.events(),
|
||||||
|
provided.main(),
|
||||||
|
provided.modThread(),
|
||||||
|
provided.async(),
|
||||||
|
provided.storage()
|
||||||
|
);
|
||||||
|
|
||||||
|
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
|
||||||
|
}
|
||||||
|
|
||||||
|
return List.copyOf(loaded);
|
||||||
|
}
|
||||||
|
catch (ModLoadException | RuntimeException e)
|
||||||
|
{
|
||||||
|
ModLoader.close(loaders.values());
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Mod create(ModDescriptor descriptor, ClassLoader loader, ModContext context) throws ModLoadException
|
||||||
|
{
|
||||||
|
String id = descriptor.id();
|
||||||
|
|
||||||
|
Constructor<? extends Mod> constructor = ModLoader.constructor(descriptor, loader);
|
||||||
|
|
||||||
|
Mod mod;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
mod = ScopedValue.where(ModBinding.CONTEXT, context).call(constructor::newInstance);
|
||||||
|
}
|
||||||
|
catch (InvocationTargetException e)
|
||||||
|
{
|
||||||
|
throw new ModLoadException(ModLoader.sentence("'" + id + "': the constructor of '" + descriptor.entrypoint() + "' threw " + e.getCause()), e.getCause());
|
||||||
|
}
|
||||||
|
catch (ReflectiveOperationException | LinkageError e)
|
||||||
|
{
|
||||||
|
throw new ModLoadException(ModLoader.sentence("'" + id + "': cannot create '" + descriptor.entrypoint() + "': " + e), e);
|
||||||
|
}
|
||||||
|
|
||||||
|
try { mod.onLoad(); }
|
||||||
|
catch (Exception e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() threw " + e), e); }
|
||||||
|
catch (LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': onLoad() failed with " + e), e); }
|
||||||
|
|
||||||
|
return mod;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Constructor<? extends Mod> constructor(ModDescriptor descriptor, ClassLoader loader) throws ModLoadException
|
||||||
|
{
|
||||||
|
String id = descriptor.id();
|
||||||
|
String entrypoint = descriptor.entrypoint();
|
||||||
|
|
||||||
|
Class<?> type;
|
||||||
|
|
||||||
|
try { type = Class.forName(entrypoint, false, loader); }
|
||||||
|
catch (ClassNotFoundException | LinkageError e) { throw new ModLoadException(ModLoader.sentence("'" + id + "': entry point '" + entrypoint + "' cannot be loaded: " + e), e); }
|
||||||
|
|
||||||
|
if (!Mod.class.isAssignableFrom(type))
|
||||||
|
throw new ModLoadException(List.of("'" + id + "': entry point '" + entrypoint + "' does not extend '" + Mod.class.getName() + "'."));
|
||||||
|
|
||||||
|
if (Modifier.isAbstract(type.getModifiers()))
|
||||||
|
throw new ModLoadException(List.of("'" + id + "': entry point '" + entrypoint + "' is abstract."));
|
||||||
|
|
||||||
|
try { return type.asSubclass(Mod.class).getConstructor(); }
|
||||||
|
catch (NoSuchMethodException e) { throw new ModLoadException("'" + id + "': entry point '" + entrypoint + "' has no public constructor without parameters.", e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code text} ending with a period; exception messages often have one already. */
|
||||||
|
private static String sentence(String text) { return text.endsWith(".") ? text : text + "."; }
|
||||||
|
|
||||||
|
private static void close(Iterable<ModClassLoader> loaders)
|
||||||
|
{
|
||||||
|
for (ModClassLoader loader : loaders) {
|
||||||
|
try { loader.close(); }
|
||||||
|
catch (IOException e) { /* the server stops anyway */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks the API version, the game versions, and the dependencies of discovered mods, and orders
|
||||||
|
* them so that every mod comes after its dependencies (otherwise by id).
|
||||||
|
*/
|
||||||
|
public final class ModResolver
|
||||||
|
{
|
||||||
|
private ModResolver() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the enabled mods in load order; disabled mods are left out.
|
||||||
|
*
|
||||||
|
* @param api the running ZomboidForge API version, or {@code null} to skip the API check
|
||||||
|
* (development builds)
|
||||||
|
* @throws ModLoadException listing every problem of every enabled mod
|
||||||
|
*/
|
||||||
|
public static List<ModDiscovery.Candidate> resolve(List<ModDiscovery.Candidate> candidates, GameVersion game, @Nullable ModVersion api) throws ModLoadException
|
||||||
|
{
|
||||||
|
Map<String, ModDiscovery.Candidate> byId = candidates.stream().filter(ModDiscovery.Candidate::enabled).collect(Collectors.toMap(ModDiscovery.Candidate::id, Function.identity(), (a, b) -> a, TreeMap::new));
|
||||||
|
Set<String> disabled = candidates.stream().filter(candidate -> !candidate.enabled()).map(ModDiscovery.Candidate::id).collect(Collectors.toSet());
|
||||||
|
List<String> problems = new ArrayList<>();
|
||||||
|
|
||||||
|
for (ModDiscovery.Candidate candidate : byId.values())
|
||||||
|
{
|
||||||
|
ModDescriptor descriptor = candidate.descriptor();
|
||||||
|
String id = descriptor.id();
|
||||||
|
|
||||||
|
if (api != null && !api.providesApi(descriptor.api()))
|
||||||
|
problems.add("'" + id + "': built against ZomboidForge API " + descriptor.api() + ", the server provides " + api + ".");
|
||||||
|
|
||||||
|
for (String previous : descriptor.previousIds()) {
|
||||||
|
if (byId.containsKey(previous)) problems.add("'" + id + "': 'previous_ids' contains '" + previous + "', which is installed as a mod.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!descriptor.game().isEmpty() && descriptor.game().stream().noneMatch(game::matches))
|
||||||
|
problems.add("'" + id + "': supports Project Zomboid " + descriptor.game() + ", the server runs " + game + ".");
|
||||||
|
|
||||||
|
for (Map.Entry<String, ModVersion> dependency : new TreeMap<>(descriptor.dependencies()).entrySet())
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate installed = byId.get(dependency.getKey());
|
||||||
|
|
||||||
|
if (installed == null && disabled.contains(dependency.getKey()))
|
||||||
|
problems.add("'" + id + "': requires '" + dependency.getKey() + "', which is disabled in its config.toml.");
|
||||||
|
else if (installed == null)
|
||||||
|
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, which is not installed.");
|
||||||
|
else if (installed.descriptor().version().compareTo(dependency.getValue()) < 0)
|
||||||
|
problems.add("'" + id + "': requires '" + dependency.getKey() + "' " + dependency.getValue() + " or newer, " + installed.descriptor().version() + " is installed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||||
|
|
||||||
|
return new Order(byId).sorted();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Depth-first ordering that reports dependency cycles. */
|
||||||
|
private static final class Order
|
||||||
|
{
|
||||||
|
private final Map<String, ModDiscovery.Candidate> byId;
|
||||||
|
private final Set<String> done = new HashSet<>();
|
||||||
|
private final LinkedHashSet<String> visiting = new LinkedHashSet<>();
|
||||||
|
private final List<ModDiscovery.Candidate> sorted = new ArrayList<>();
|
||||||
|
private final List<String> problems = new ArrayList<>();
|
||||||
|
|
||||||
|
private Order(Map<String, ModDiscovery.Candidate> byId) { this.byId = byId; }
|
||||||
|
|
||||||
|
private List<ModDiscovery.Candidate> sorted() throws ModLoadException
|
||||||
|
{
|
||||||
|
for (String id : this.byId.keySet()) this.visit(id);
|
||||||
|
|
||||||
|
if (!this.problems.isEmpty()) throw new ModLoadException(this.problems);
|
||||||
|
|
||||||
|
return List.copyOf(this.sorted);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void visit(String id)
|
||||||
|
{
|
||||||
|
if (this.done.contains(id)) return;
|
||||||
|
|
||||||
|
if (!this.visiting.add(id))
|
||||||
|
{
|
||||||
|
List<String> path = new ArrayList<>(this.visiting);
|
||||||
|
List<String> cycle = new ArrayList<>(path.subList(path.indexOf(id), path.size()));
|
||||||
|
cycle.add(id);
|
||||||
|
|
||||||
|
this.problems.add("'" + id + "': dependency cycle " + cycle.stream().map(element -> "'" + element + "'").collect(Collectors.joining(" -> ")) + ".");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ModDiscovery.Candidate candidate = Objects.requireNonNull(this.byId.get(id));
|
||||||
|
for (String dependency : new TreeMap<>(candidate.descriptor().dependencies()).keySet()) this.visit(dependency);
|
||||||
|
|
||||||
|
this.visiting.remove(id);
|
||||||
|
|
||||||
|
if (this.done.add(id)) this.sorted.add(candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.AsyncExecutor;
|
||||||
|
import dev.overlord.zomboidforge.api.Events;
|
||||||
|
import dev.overlord.zomboidforge.api.MainThread;
|
||||||
|
import dev.overlord.zomboidforge.api.ModThread;
|
||||||
|
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||||
|
|
||||||
|
/** The threads, event registration, and storage of one mod, created before its entry point. */
|
||||||
|
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async, ModStorage storage)
|
||||||
|
{
|
||||||
|
/** Creates the services of one mod. */
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface Factory
|
||||||
|
{
|
||||||
|
ModServices create(String id, System.Logger logger);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,384 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import org.objectweb.asm.ClassReader;
|
||||||
|
import org.objectweb.asm.ClassVisitor;
|
||||||
|
import org.objectweb.asm.FieldVisitor;
|
||||||
|
import org.objectweb.asm.Handle;
|
||||||
|
import org.objectweb.asm.Label;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.RecordComponentVisitor;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.UncheckedIOException;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarFile;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks the classes of resolved mods before any of them is loaded:
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>no class in a ZomboidForge package, and no class in the mod's own jar with the name of a
|
||||||
|
* game class;</li>
|
||||||
|
* <li>no use of ZomboidForge classes outside the API;</li>
|
||||||
|
* <li>a mod that uses classes of the Project Zomboid jar declares {@code game} versions;</li>
|
||||||
|
* <li>every game class, field, and method such a mod uses exists in the running jar
|
||||||
|
* (members are looked up through superclasses and interfaces).</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* Annotations are not checked: the JVM does not load annotation types a class only carries.
|
||||||
|
*/
|
||||||
|
public final class ModVerifier
|
||||||
|
{
|
||||||
|
private static final String FORGE = "dev/overlord/zomboidforge/";
|
||||||
|
private static final String API = "dev/overlord/zomboidforge/api/";
|
||||||
|
private static final String API_INTERNAL = "dev/overlord/zomboidforge/api/internal/";
|
||||||
|
private static final int EXAMPLES = 5;
|
||||||
|
|
||||||
|
/** A field or method that a mod's code uses. */
|
||||||
|
private record Member(boolean method, String owner, String name, String desc) implements Comparable<Member>
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
public int compareTo(Member other) { return this.toString().compareTo(other.toString()); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() { return this.owner.replace('/', '.') + "." + this.name + (this.method ? "" : ":") + this.desc; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private 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()}
|
||||||
|
* @throws ModLoadException listing every problem of every mod
|
||||||
|
*/
|
||||||
|
public static void verify(List<ModDiscovery.Candidate> ordered, GameClasses game, @Nullable GameVersion version) throws ModLoadException
|
||||||
|
{
|
||||||
|
Hierarchy hierarchy = new Hierarchy(game);
|
||||||
|
Map<String, Set<String>> ownByMod = new HashMap<>();
|
||||||
|
List<String> problems = new ArrayList<>();
|
||||||
|
|
||||||
|
for (ModDiscovery.Candidate candidate : ordered)
|
||||||
|
{
|
||||||
|
String id = candidate.id();
|
||||||
|
Map<String, byte[]> own = ModVerifier.classes(candidate.jar());
|
||||||
|
Map<String, byte[]> libraries = new TreeMap<>();
|
||||||
|
|
||||||
|
for (Path library : candidate.libraries()) libraries.putAll(ModVerifier.classes(library));
|
||||||
|
|
||||||
|
ownByMod.put(id, own.keySet());
|
||||||
|
|
||||||
|
Set<String> provided = new HashSet<>(own.keySet());
|
||||||
|
provided.addAll(libraries.keySet());
|
||||||
|
for (String dependency : candidate.descriptor().dependencies().keySet()) provided.addAll(ownByMod.getOrDefault(dependency, Set.of()));
|
||||||
|
|
||||||
|
Set<String> contained = new TreeSet<>(own.keySet());
|
||||||
|
contained.addAll(libraries.keySet());
|
||||||
|
|
||||||
|
for (String name : contained) {
|
||||||
|
if (name.startsWith(ModVerifier.FORGE)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is in a ZomboidForge package.");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String name : new TreeSet<>(own.keySet())) {
|
||||||
|
if (game.contains(name)) problems.add("'" + id + "': contains '" + ModVerifier.dotted(name) + "', which is a class of Project Zomboid.");
|
||||||
|
}
|
||||||
|
|
||||||
|
References references = new References();
|
||||||
|
for (byte[] bytes : own.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||||
|
for (byte[] bytes : libraries.values()) new ClassReader(bytes).accept(references, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||||
|
|
||||||
|
Set<String> gameTypes = new TreeSet<>();
|
||||||
|
Set<String> missingTypes = new TreeSet<>();
|
||||||
|
|
||||||
|
for (String type : references.types)
|
||||||
|
{
|
||||||
|
if (JdkPackages.contains(type) || provided.contains(type)) continue;
|
||||||
|
|
||||||
|
if (type.startsWith(ModVerifier.FORGE) && (!type.startsWith(ModVerifier.API) || type.startsWith(ModVerifier.API_INTERNAL)))
|
||||||
|
problems.add("'" + id + "': uses '" + ModVerifier.dotted(type) + "', which is internal to ZomboidForge.");
|
||||||
|
else if (game.contains(type))
|
||||||
|
gameTypes.add(type);
|
||||||
|
else if (!type.startsWith(ModVerifier.FORGE) && game.containsPackageOf(type))
|
||||||
|
missingTypes.add(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean declaresGame = !candidate.descriptor().game().isEmpty();
|
||||||
|
|
||||||
|
if (!declaresGame && !(gameTypes.isEmpty() && missingTypes.isEmpty()))
|
||||||
|
{
|
||||||
|
Set<String> used = new TreeSet<>(gameTypes);
|
||||||
|
used.addAll(missingTypes);
|
||||||
|
|
||||||
|
problems.add("'" + id + "': uses classes of the Project Zomboid jar (" + ModVerifier.examples(used) + ") but declares no 'game' versions in mod.toml.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> linkage = new ArrayList<>();
|
||||||
|
|
||||||
|
for (String type : missingTypes) linkage.add("'" + ModVerifier.dotted(type) + "'");
|
||||||
|
|
||||||
|
for (Member member : references.members) {
|
||||||
|
if (gameTypes.contains(member.owner()) && !hierarchy.has(member)) linkage.add("'" + member + "'");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!linkage.isEmpty())
|
||||||
|
problems.add("'" + id + "': uses " + ModVerifier.examples(linkage) + ", which " + (linkage.size() == 1 ? "does" : "do") + " not exist in " + (version == null ? "the game jar" : "Project Zomboid " + version) + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!problems.isEmpty()) throw new ModLoadException(problems);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Internal class name to class file, for every class in {@code jar} outside {@code META-INF/}. */
|
||||||
|
private static Map<String, byte[]> classes(Path jar)
|
||||||
|
{
|
||||||
|
Map<String, byte[]> classes = new TreeMap<>();
|
||||||
|
|
||||||
|
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/") || name.endsWith("module-info.class")) continue;
|
||||||
|
|
||||||
|
try (InputStream in = file.getInputStream(entry)) { classes.put(name.substring(0, name.length() - ".class".length()), in.readAllBytes()); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (IOException e) { throw new UncheckedIOException("Cannot read '" + jar + "'.", e); }
|
||||||
|
|
||||||
|
return classes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first {@value #EXAMPLES} elements, quoted unless already quoted, and how many more there are. */
|
||||||
|
private static String examples(Iterable<String> elements)
|
||||||
|
{
|
||||||
|
List<String> all = new ArrayList<>();
|
||||||
|
for (String element : elements) all.add(element.startsWith("'") ? element : "'" + ModVerifier.dotted(element) + "'");
|
||||||
|
|
||||||
|
String shown = all.stream().limit(ModVerifier.EXAMPLES).collect(Collectors.joining(", "));
|
||||||
|
return all.size() > ModVerifier.EXAMPLES ? shown + " and " + (all.size() - ModVerifier.EXAMPLES) + " more" : shown;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String dotted(String internalName) { return internalName.replace('/', '.'); }
|
||||||
|
|
||||||
|
/** Collects the classes and members that code uses; skips annotations and debug information. */
|
||||||
|
private static final class References extends ClassVisitor
|
||||||
|
{
|
||||||
|
private final Set<String> types = new TreeSet<>();
|
||||||
|
private final Set<Member> members = new TreeSet<>();
|
||||||
|
|
||||||
|
private References() { super(Opcodes.ASM9); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(int version, int access, String name, @Nullable String signature, @Nullable String superName, String @Nullable [] interfaces)
|
||||||
|
{
|
||||||
|
if (superName != null) this.type(superName);
|
||||||
|
if (interfaces != null) for (String type : interfaces) this.type(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
|
||||||
|
{
|
||||||
|
this.descriptor(descriptor);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public @Nullable RecordComponentVisitor visitRecordComponent(String name, String descriptor, @Nullable String signature)
|
||||||
|
{
|
||||||
|
this.descriptor(descriptor);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
|
||||||
|
{
|
||||||
|
this.descriptor(descriptor);
|
||||||
|
if (exceptions != null) for (String type : exceptions) this.type(type);
|
||||||
|
|
||||||
|
References references = this;
|
||||||
|
|
||||||
|
return new MethodVisitor(Opcodes.ASM9)
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
public void visitTypeInsn(int opcode, String type) { references.type(type); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { references.member(false, owner, name, descriptor); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) { references.member(true, owner, name, descriptor); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitInvokeDynamicInsn(String name, String descriptor, Handle bootstrap, Object... arguments)
|
||||||
|
{
|
||||||
|
references.descriptor(descriptor);
|
||||||
|
references.constant(bootstrap);
|
||||||
|
|
||||||
|
for (Object argument : arguments) references.constant(argument);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitLdcInsn(Object value) { references.constant(value); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitMultiANewArrayInsn(String descriptor, int dimensions) { references.descriptor(descriptor); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitTryCatchBlock(Label start, Label end, Label handler, @Nullable String type)
|
||||||
|
{
|
||||||
|
if (type != null) references.type(type);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void member(boolean method, String owner, String name, String descriptor)
|
||||||
|
{
|
||||||
|
this.type(owner);
|
||||||
|
this.descriptor(descriptor);
|
||||||
|
|
||||||
|
if (!owner.startsWith("[")) this.members.add(new Member(method, owner, name, descriptor));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void constant(Object value)
|
||||||
|
{
|
||||||
|
switch (value)
|
||||||
|
{
|
||||||
|
case Handle handle -> this.member(handle.getTag() > Opcodes.H_PUTSTATIC, handle.getOwner(), handle.getName(), handle.getDesc());
|
||||||
|
case Type type -> this.descriptor(type.getDescriptor());
|
||||||
|
default -> { /* numbers, strings, dynamic constants */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An internal class name, or an array descriptor as used by {@code anewarray} and {@code checkcast}. */
|
||||||
|
private void type(String name)
|
||||||
|
{
|
||||||
|
if (name.startsWith("[")) this.descriptor(name);
|
||||||
|
else this.types.add(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void descriptor(String descriptor)
|
||||||
|
{
|
||||||
|
Type type = Type.getType(descriptor);
|
||||||
|
|
||||||
|
if (type.getSort() == Type.METHOD)
|
||||||
|
{
|
||||||
|
for (Type argument : type.getArgumentTypes()) this.add(argument);
|
||||||
|
this.add(type.getReturnType());
|
||||||
|
}
|
||||||
|
else this.add(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void add(Type type)
|
||||||
|
{
|
||||||
|
Type element = type.getSort() == Type.ARRAY ? type.getElementType() : type;
|
||||||
|
if (element.getSort() == Type.OBJECT) this.types.add(element.getInternalName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fields and methods of game and JDK classes, read from their class files. */
|
||||||
|
private static final class Hierarchy
|
||||||
|
{
|
||||||
|
private record Info(@Nullable String superName, List<String> interfaces, Set<String> fields, Set<String> methods) {}
|
||||||
|
|
||||||
|
private final GameClasses game;
|
||||||
|
private final Map<String, @Nullable Info> cache = new HashMap<>();
|
||||||
|
|
||||||
|
private Hierarchy(GameClasses game) { this.game = game; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether {@code member} resolves in its owner, a superclass, or a superinterface.
|
||||||
|
* Constructors only count in the owner. Supertypes whose class files cannot be read
|
||||||
|
* count as having every member.
|
||||||
|
*/
|
||||||
|
private boolean has(Member member)
|
||||||
|
{
|
||||||
|
String key = member.name() + member.desc();
|
||||||
|
Deque<String> pending = new ArrayDeque<>(List.of(member.owner()));
|
||||||
|
Set<String> seen = new HashSet<>();
|
||||||
|
|
||||||
|
while (!pending.isEmpty())
|
||||||
|
{
|
||||||
|
String type = pending.pop();
|
||||||
|
if (!seen.add(type)) continue;
|
||||||
|
|
||||||
|
Info info = this.info(type);
|
||||||
|
if (info == null) return !type.equals(member.owner());
|
||||||
|
|
||||||
|
if ((member.method() ? info.methods() : info.fields()).contains(key)) return true;
|
||||||
|
if (member.method() && member.name().equals("<init>")) return false;
|
||||||
|
|
||||||
|
if (info.superName() != null) pending.add(info.superName());
|
||||||
|
pending.addAll(info.interfaces());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Interface methods may also be declared by java.lang.Object.
|
||||||
|
return member.method() && !member.owner().equals("java/lang/Object") && this.has(new Member(true, "java/lang/Object", member.name(), member.desc()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Info info(String type)
|
||||||
|
{
|
||||||
|
if (this.cache.containsKey(type)) return this.cache.get(type);
|
||||||
|
|
||||||
|
Info info = null;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
byte[] bytes = this.game.contains(type) ? this.game.read(type) : JdkPackages.contains(type) ? Hierarchy.jdkClass(type) : null;
|
||||||
|
if (bytes != null) info = Hierarchy.read(bytes);
|
||||||
|
}
|
||||||
|
catch (IOException e) { throw new UncheckedIOException("Cannot read class '" + type + "'.", e); }
|
||||||
|
|
||||||
|
this.cache.put(type, info);
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte @Nullable [] jdkClass(String type) throws IOException
|
||||||
|
{
|
||||||
|
try (InputStream in = ClassLoader.getSystemResourceAsStream(type + ".class")) { return in == null ? null : in.readAllBytes(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Info read(byte[] bytes)
|
||||||
|
{
|
||||||
|
ClassReader reader = new ClassReader(bytes);
|
||||||
|
Set<String> fields = new HashSet<>();
|
||||||
|
Set<String> methods = new HashSet<>();
|
||||||
|
|
||||||
|
reader.accept(new ClassVisitor(Opcodes.ASM9)
|
||||||
|
{
|
||||||
|
@Override
|
||||||
|
public @Nullable FieldVisitor visitField(int access, String name, String descriptor, @Nullable String signature, @Nullable Object value)
|
||||||
|
{
|
||||||
|
fields.add(name + descriptor);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public @Nullable MethodVisitor visitMethod(int access, String name, String descriptor, @Nullable String signature, String @Nullable [] exceptions)
|
||||||
|
{
|
||||||
|
methods.add(name + descriptor);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
|
||||||
|
|
||||||
|
return new Info(reader.getSuperName(), List.of(reader.getInterfaces()), fields, methods);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Semantic version of a mod or of the ZomboidForge API: {@code major[.minor[.patch]][-pre-release]},
|
||||||
|
* missing parts are 0. A pre-release sorts before the release with the same numbers.
|
||||||
|
*/
|
||||||
|
public record ModVersion(int major, int minor, int patch, @Nullable String preRelease) implements Comparable<ModVersion>
|
||||||
|
{
|
||||||
|
// At most 9 digits per number, so every number fits an int.
|
||||||
|
private static final Pattern FORMAT = Pattern.compile("(\\d{1,9})(?:\\.(\\d{1,9}))?(?:\\.(\\d{1,9}))?(?:-([0-9A-Za-z.-]+))?");
|
||||||
|
|
||||||
|
private static final Comparator<ModVersion> ORDER = Comparator
|
||||||
|
.comparingInt(ModVersion::major)
|
||||||
|
.thenComparingInt(ModVersion::minor)
|
||||||
|
.thenComparingInt(ModVersion::patch)
|
||||||
|
.thenComparing(ModVersion::preRelease, Comparator.nullsLast(Comparator.naturalOrder()));
|
||||||
|
|
||||||
|
public static ModVersion parse(String text)
|
||||||
|
{
|
||||||
|
return ModVersion.tryParse(text).orElseThrow(() -> new IllegalArgumentException("Not a version: '" + text + "'."));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Optional<ModVersion> tryParse(String text)
|
||||||
|
{
|
||||||
|
Matcher matcher = ModVersion.FORMAT.matcher(text.trim());
|
||||||
|
if (!matcher.matches()) return Optional.empty();
|
||||||
|
|
||||||
|
return Optional.of(new ModVersion(
|
||||||
|
Integer.parseInt(matcher.group(1)),
|
||||||
|
ModVersion.partOrZero(matcher.group(2)),
|
||||||
|
ModVersion.partOrZero(matcher.group(3)),
|
||||||
|
matcher.group(4)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a mod built against the API version {@code required} runs with this API version:
|
||||||
|
* same major version and this version not older. Before 1.0 the minor version must match
|
||||||
|
* as well, because 0.x releases may break the API.
|
||||||
|
*/
|
||||||
|
public boolean providesApi(ModVersion required)
|
||||||
|
{
|
||||||
|
if (this.major != required.major || this.compareTo(required) < 0) return false;
|
||||||
|
|
||||||
|
return this.major != 0 || this.minor == required.minor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(ModVersion other) { return ModVersion.ORDER.compare(this, other); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString()
|
||||||
|
{
|
||||||
|
String numbers = this.major + "." + this.minor + "." + this.patch;
|
||||||
|
return this.preRelease == null ? numbers : numbers + "-" + this.preRelease;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int partOrZero(@Nullable String part) { return part == null ? 0 : Integer.parseInt(part); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* Mod discovery, validation, and loading from {@code <forge>/mods}.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.runtime;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.Event;
|
||||||
|
import dev.overlord.zomboidforge.api.Events;
|
||||||
|
import dev.overlord.zomboidforge.api.MainThreadEvent;
|
||||||
|
import dev.overlord.zomboidforge.api.Subscription;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.RejectedExecutionException;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Event dispatch for every mod. Listeners are matched by the event's exact class and called in
|
||||||
|
* registration order. Registration replaces the listener array of a class, so {@link #post}
|
||||||
|
* iterates a snapshot without locks.
|
||||||
|
*/
|
||||||
|
public final class EventBus
|
||||||
|
{
|
||||||
|
/** Failures after which a listener is removed. */
|
||||||
|
static final int MAX_FAILURES = 10;
|
||||||
|
|
||||||
|
private final Map<Class<?>, Listener[]> listeners = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
private volatile boolean closed;
|
||||||
|
|
||||||
|
/** Registration for one mod; its listeners are tagged with {@code id}. */
|
||||||
|
public Events forMod(String id, Executor modThread, System.Logger logger) { return new ModEvents(id, modThread, logger); }
|
||||||
|
|
||||||
|
/** Whether any listener is registered for exactly this class. */
|
||||||
|
public boolean hasListeners(Class<? extends Event> type) { return this.listeners.containsKey(type); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delivers {@code event}: main listeners run now, on the calling thread, which must be the
|
||||||
|
* main thread; mod-thread listeners get a task on their mod's thread. A listener's exception
|
||||||
|
* is logged and never reaches the caller.
|
||||||
|
*/
|
||||||
|
public void post(Event event)
|
||||||
|
{
|
||||||
|
if (this.closed) return;
|
||||||
|
|
||||||
|
Listener[] listeners = this.listeners.get(event.getClass());
|
||||||
|
if (listeners == null) return;
|
||||||
|
|
||||||
|
for (Listener listener : listeners) listener.deliver(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stops delivering events. */
|
||||||
|
public void close() { this.closed = true; }
|
||||||
|
|
||||||
|
private synchronized void add(Listener listener)
|
||||||
|
{
|
||||||
|
Listener[] current = this.listeners.getOrDefault(listener.type, new Listener[0]);
|
||||||
|
Listener[] updated = Arrays.copyOf(current, current.length + 1);
|
||||||
|
|
||||||
|
updated[current.length] = listener;
|
||||||
|
this.listeners.put(listener.type, updated);
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void remove(Listener listener)
|
||||||
|
{
|
||||||
|
Listener[] current = this.listeners.get(listener.type);
|
||||||
|
if (current == null) return;
|
||||||
|
|
||||||
|
Listener[] updated = Arrays.stream(current).filter(other -> other != listener).toArray(Listener[]::new);
|
||||||
|
|
||||||
|
if (updated.length == 0) this.listeners.remove(listener.type);
|
||||||
|
else this.listeners.put(listener.type, updated);
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class ModEvents implements Events
|
||||||
|
{
|
||||||
|
private final String id;
|
||||||
|
private final Executor modThread;
|
||||||
|
private final System.Logger logger;
|
||||||
|
|
||||||
|
private ModEvents(String id, Executor modThread, System.Logger logger)
|
||||||
|
{
|
||||||
|
this.id = id;
|
||||||
|
this.modThread = modThread;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <E extends Event> Subscription onMain(Class<E> type, Consumer<? super E> listener) { return this.register(type, listener, null); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <E extends Event> Subscription onModThread(Class<E> type, Consumer<? super E> listener)
|
||||||
|
{
|
||||||
|
if (MainThreadEvent.class.isAssignableFrom(type))
|
||||||
|
throw new IllegalArgumentException("'" + type.getName() + "' is a main-thread event; listen with onMain().");
|
||||||
|
|
||||||
|
return this.register(type, listener, this.modThread);
|
||||||
|
}
|
||||||
|
|
||||||
|
private <E extends Event> Subscription register(Class<E> type, Consumer<? super E> listener, @Nullable Executor executor)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(type, "type");
|
||||||
|
Objects.requireNonNull(listener, "listener");
|
||||||
|
|
||||||
|
Listener registered = new Listener(this.id, type, event -> listener.accept(type.cast(event)), executor, this.logger);
|
||||||
|
EventBus.this.add(registered);
|
||||||
|
|
||||||
|
return registered;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class Listener implements Subscription
|
||||||
|
{
|
||||||
|
private final String mod;
|
||||||
|
private final Class<?> type;
|
||||||
|
private final String kind;
|
||||||
|
private final Consumer<Object> action;
|
||||||
|
private final @Nullable Executor executor;
|
||||||
|
private final System.Logger logger;
|
||||||
|
private final AtomicInteger failures = new AtomicInteger();
|
||||||
|
|
||||||
|
private volatile boolean active = true;
|
||||||
|
|
||||||
|
private Listener(String mod, Class<?> type, Consumer<Object> action, @Nullable Executor executor, System.Logger logger)
|
||||||
|
{
|
||||||
|
this.mod = mod;
|
||||||
|
this.type = type;
|
||||||
|
this.kind = "listener " + type.getSimpleName();
|
||||||
|
this.action = action;
|
||||||
|
this.executor = executor;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void cancel()
|
||||||
|
{
|
||||||
|
this.active = false;
|
||||||
|
EventBus.this.remove(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void deliver(Event event)
|
||||||
|
{
|
||||||
|
if (!this.active) return;
|
||||||
|
|
||||||
|
if (this.executor == null) {
|
||||||
|
this.invoke(event);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try { this.executor.execute(() -> this.invoke(event)); }
|
||||||
|
catch (RejectedExecutionException e) { /* the mod's thread has been shut down */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void invoke(Event event)
|
||||||
|
{
|
||||||
|
if (!this.active) return;
|
||||||
|
|
||||||
|
Throwable failure = ModTaskEvent.run(this.mod, this.kind, () -> this.action.accept(event));
|
||||||
|
if (failure == null) return;
|
||||||
|
|
||||||
|
int count = this.failures.incrementAndGet();
|
||||||
|
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' threw (failure " + count + " of " + EventBus.MAX_FAILURES + ").", failure);
|
||||||
|
|
||||||
|
if (count >= EventBus.MAX_FAILURES)
|
||||||
|
{
|
||||||
|
this.cancel();
|
||||||
|
this.logger.log(System.Logger.Level.ERROR, "Listener for '" + this.type.getSimpleName() + "' removed after " + EventBus.MAX_FAILURES + " failures.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.runtime;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.MainThread;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.PriorityQueue;
|
||||||
|
import java.util.Queue;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||||
|
import java.util.concurrent.RejectedExecutionException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The main-thread tasks of every mod: one queue per mod, drained round-robin by
|
||||||
|
* {@link #drain()} once per tick until the time budget is used up. A task in progress is never
|
||||||
|
* interrupted, so the budget is a soft limit; at least one task runs per tick while any is
|
||||||
|
* queued.
|
||||||
|
*/
|
||||||
|
public final class MainThreadQueue
|
||||||
|
{
|
||||||
|
private record Task(Runnable action, @Nullable CompletableFuture<?> future) {}
|
||||||
|
|
||||||
|
private record Delayed(long due, long sequence, Task task) {}
|
||||||
|
|
||||||
|
private volatile long budgetNanos;
|
||||||
|
private volatile @Nullable Thread mainThread;
|
||||||
|
private volatile boolean closed;
|
||||||
|
private volatile ModQueue[] queues = new ModQueue[0];
|
||||||
|
private volatile long tick;
|
||||||
|
|
||||||
|
/** Index of the mod queue the next {@link #drain()} starts with; main thread only. */
|
||||||
|
private int next;
|
||||||
|
|
||||||
|
public MainThreadQueue(Duration budget) { this.budgetNanos = budget.toNanos(); }
|
||||||
|
|
||||||
|
/** Sets the time per {@link #drain()} for queued tasks. */
|
||||||
|
public void budget(Duration budget) { this.budgetNanos = budget.toNanos(); }
|
||||||
|
|
||||||
|
/** Makes the calling thread the main thread. */
|
||||||
|
public void bindToCurrentThread() { this.mainThread = Thread.currentThread(); }
|
||||||
|
|
||||||
|
public boolean isMainThread() { return Thread.currentThread() == this.mainThread; }
|
||||||
|
|
||||||
|
/** Number of the last frame {@link #drain()} ran for; 0 before the first. */
|
||||||
|
public long tick() { return this.tick; }
|
||||||
|
|
||||||
|
/** The {@link MainThread} of one mod; its tasks are tagged with {@code id}. */
|
||||||
|
public synchronized MainThread forMod(String id, System.Logger logger)
|
||||||
|
{
|
||||||
|
ModQueue queue = new ModQueue(id, logger);
|
||||||
|
ModQueue[] queues = Arrays.copyOf(this.queues, this.queues.length + 1);
|
||||||
|
|
||||||
|
queues[queues.length - 1] = queue;
|
||||||
|
this.queues = queues;
|
||||||
|
|
||||||
|
return queue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the next frame: moves due delayed tasks into the queues, then runs queued tasks
|
||||||
|
* round-robin until every queue is empty or the budget is used up. Main thread only.
|
||||||
|
*/
|
||||||
|
public void drain()
|
||||||
|
{
|
||||||
|
long deadline = System.nanoTime() + this.budgetNanos;
|
||||||
|
ModQueue[] queues = this.queues;
|
||||||
|
long tick = this.tick + 1;
|
||||||
|
|
||||||
|
this.tick = tick;
|
||||||
|
|
||||||
|
for (ModQueue queue : queues) queue.promote(tick);
|
||||||
|
|
||||||
|
int count = queues.length;
|
||||||
|
int index = count == 0 ? 0 : this.next % count;
|
||||||
|
int empty = 0;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (empty < count && !this.closed)
|
||||||
|
{
|
||||||
|
ModQueue queue = queues[index];
|
||||||
|
index = (index + 1) % count;
|
||||||
|
|
||||||
|
Task task = queue.tasks.poll();
|
||||||
|
|
||||||
|
if (task == null) {
|
||||||
|
empty++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
empty = 0;
|
||||||
|
queue.run(task.action());
|
||||||
|
|
||||||
|
if (System.nanoTime() >= deadline) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
this.next = index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rejects further tasks and cancels the queued ones (their futures are cancelled). Any thread. */
|
||||||
|
public void close()
|
||||||
|
{
|
||||||
|
this.closed = true;
|
||||||
|
|
||||||
|
for (ModQueue queue : this.queues) queue.cancelAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class ModQueue implements MainThread
|
||||||
|
{
|
||||||
|
private final String id;
|
||||||
|
private final System.Logger logger;
|
||||||
|
private final Queue<Task> tasks = new ConcurrentLinkedQueue<>();
|
||||||
|
private final PriorityQueue<Delayed> delayed = new PriorityQueue<>(Comparator.comparingLong(Delayed::due).thenComparingLong(Delayed::sequence));
|
||||||
|
|
||||||
|
/** Guarded by {@link #delayed}. */
|
||||||
|
private long sequence;
|
||||||
|
|
||||||
|
private ModQueue(String id, System.Logger logger)
|
||||||
|
{
|
||||||
|
this.id = id;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void execute(Runnable task)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(task, "task");
|
||||||
|
this.requireOpen();
|
||||||
|
|
||||||
|
if (MainThreadQueue.this.isMainThread()) this.run(task);
|
||||||
|
else this.enqueue(new Task(task, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> CompletableFuture<T> submit(Callable<T> task)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(task, "task");
|
||||||
|
this.requireOpen();
|
||||||
|
|
||||||
|
CompletableFuture<T> future = new CompletableFuture<>();
|
||||||
|
Runnable action = () -> {
|
||||||
|
try { future.complete(task.call()); }
|
||||||
|
catch (Throwable t) { future.completeExceptionally(t); }
|
||||||
|
};
|
||||||
|
|
||||||
|
if (MainThreadQueue.this.isMainThread()) this.run(action);
|
||||||
|
else this.enqueue(new Task(action, future));
|
||||||
|
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void runLater(int ticks, Runnable task)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(task, "task");
|
||||||
|
if (ticks < 1) throw new IllegalArgumentException("'ticks' must be at least 1, found " + ticks + ".");
|
||||||
|
|
||||||
|
this.requireOpen();
|
||||||
|
|
||||||
|
synchronized (this.delayed) { this.delayed.add(new Delayed(MainThreadQueue.this.tick + ticks, this.sequence++, new Task(task, null))); }
|
||||||
|
|
||||||
|
if (MainThreadQueue.this.closed) this.cancelAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isMainThread() { return MainThreadQueue.this.isMainThread(); }
|
||||||
|
|
||||||
|
private void enqueue(Task task)
|
||||||
|
{
|
||||||
|
this.tasks.add(task);
|
||||||
|
|
||||||
|
// close() may have run between requireOpen() and add().
|
||||||
|
if (MainThreadQueue.this.closed) this.cancelAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void promote(long tick)
|
||||||
|
{
|
||||||
|
synchronized (this.delayed)
|
||||||
|
{
|
||||||
|
while (!this.delayed.isEmpty() && this.delayed.element().due() <= tick) this.tasks.add(this.delayed.remove().task());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void run(Runnable action)
|
||||||
|
{
|
||||||
|
Throwable failure = ModTaskEvent.run(this.id, "task", action);
|
||||||
|
if (failure != null) this.logger.log(System.Logger.Level.ERROR, "A main-thread task threw.", failure);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cancelAll()
|
||||||
|
{
|
||||||
|
for (Task task = this.tasks.poll(); task != null; task = this.tasks.poll())
|
||||||
|
{
|
||||||
|
CompletableFuture<?> future = task.future();
|
||||||
|
if (future != null) future.cancel(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized (this.delayed) { this.delayed.clear(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireOpen()
|
||||||
|
{
|
||||||
|
if (MainThreadQueue.this.closed) throw new RejectedExecutionException("The server is stopping; '" + this.id + "' cannot queue main-thread tasks.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.runtime;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import jdk.jfr.Category;
|
||||||
|
import jdk.jfr.Description;
|
||||||
|
import jdk.jfr.Label;
|
||||||
|
import jdk.jfr.Name;
|
||||||
|
import jdk.jfr.StackTrace;
|
||||||
|
|
||||||
|
/** JFR event for main-thread work of a mod: a queued task or an event listener. */
|
||||||
|
@Name("zomboidforge.ModTask")
|
||||||
|
@Label("Mod Task")
|
||||||
|
@Category("ZomboidForge")
|
||||||
|
@Description("Main-thread work of a mod: a queued task or an event listener")
|
||||||
|
@StackTrace(false)
|
||||||
|
final class ModTaskEvent extends jdk.jfr.Event
|
||||||
|
{
|
||||||
|
@Label("Mod")
|
||||||
|
String mod = "";
|
||||||
|
|
||||||
|
/** {@code task}, or {@code listener <event class>}. */
|
||||||
|
@Label("Kind")
|
||||||
|
String kind = "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs {@code action} as a {@code zomboidforge.ModTask} event. Mod code must not end the
|
||||||
|
* calling thread's work, so every failure is returned instead of thrown, including errors
|
||||||
|
* and checked exceptions thrown without being declared.
|
||||||
|
*
|
||||||
|
* @return the failure, or {@code null} when {@code action} returned normally
|
||||||
|
*/
|
||||||
|
static @Nullable Throwable run(String mod, String kind, Runnable action)
|
||||||
|
{
|
||||||
|
ModTaskEvent event = new ModTaskEvent();
|
||||||
|
event.begin();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
action.run();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (Throwable t)
|
||||||
|
{
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
event.end();
|
||||||
|
|
||||||
|
if (event.shouldCommit())
|
||||||
|
{
|
||||||
|
event.mod = mod;
|
||||||
|
event.kind = kind;
|
||||||
|
event.commit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.runtime;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.AsyncExecutor;
|
||||||
|
import dev.overlord.zomboidforge.api.ModThread;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The own threads of every mod: one platform thread {@code zf-mod-<id>} that runs the mod's
|
||||||
|
* tasks in order, and virtual threads {@code zf-async-<id>-<n>} for blocking work. All threads
|
||||||
|
* are daemon threads, so they never keep the JVM alive.
|
||||||
|
*
|
||||||
|
* <p>Mods get them as {@link ModThread} and {@link AsyncExecutor}, which cannot shut the
|
||||||
|
* executors down; only {@link #shutdown} does.
|
||||||
|
*/
|
||||||
|
public final class ModThreads
|
||||||
|
{
|
||||||
|
/** The executors of one mod. */
|
||||||
|
public record ModExecutors(ModThread modThread, AsyncExecutor async) {}
|
||||||
|
|
||||||
|
/** The executors of one mod; plain fields, as the executors live until {@link #shutdown}. */
|
||||||
|
private static final class Entry
|
||||||
|
{
|
||||||
|
private final String id;
|
||||||
|
private final ModThreadExecutor modThread;
|
||||||
|
private final ExecutorService async;
|
||||||
|
|
||||||
|
private Entry(String id, ModThreadExecutor modThread, ExecutorService async)
|
||||||
|
{
|
||||||
|
this.id = id;
|
||||||
|
this.modThread = modThread;
|
||||||
|
this.async = async;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final List<Entry> entries = new ArrayList<>();
|
||||||
|
|
||||||
|
/** Creates the executors of one mod. */
|
||||||
|
public synchronized ModExecutors create(String id, System.Logger logger)
|
||||||
|
{
|
||||||
|
Entry entry = new Entry(
|
||||||
|
id,
|
||||||
|
new ModThreadExecutor(id, logger),
|
||||||
|
Executors.newThreadPerTaskExecutor(
|
||||||
|
Thread.ofVirtual()
|
||||||
|
.name("zf-async-" + id + "-", 0)
|
||||||
|
.uncaughtExceptionHandler((thread, e) -> logger.log(System.Logger.Level.ERROR, "A task on '" + thread.getName() + "' threw.", e))
|
||||||
|
.factory()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
this.entries.add(entry);
|
||||||
|
return new ModExecutors(new ModThreadHandle(entry.modThread), new AsyncHandle(entry.async));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shuts every executor down: new tasks are rejected, delayed and periodic tasks of the mod
|
||||||
|
* threads are dropped, and running or queued tasks get until {@code timeout} (for all mods
|
||||||
|
* together) to finish. Threads still running then are interrupted.
|
||||||
|
*/
|
||||||
|
public synchronized void shutdown(Duration timeout, System.Logger logger)
|
||||||
|
{
|
||||||
|
long deadline = System.nanoTime() + timeout.toNanos();
|
||||||
|
|
||||||
|
for (Entry entry : this.entries)
|
||||||
|
{
|
||||||
|
entry.modThread.shutdown();
|
||||||
|
entry.async.shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Entry entry : this.entries)
|
||||||
|
{
|
||||||
|
// '&' instead of '&&': both executors get their share of the time.
|
||||||
|
boolean finished = ModThreads.await(entry.modThread, deadline) & ModThreads.await(entry.async, deadline);
|
||||||
|
|
||||||
|
if (!finished)
|
||||||
|
{
|
||||||
|
entry.modThread.shutdownNow();
|
||||||
|
entry.async.shutdownNow();
|
||||||
|
logger.log(System.Logger.Level.WARNING, "'" + entry.id + "': threads still running after " + timeout.toMillis() / 1000.0 + " s; interrupted.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean await(ExecutorService executor, long deadline)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return executor.awaitTermination(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
|
||||||
|
}
|
||||||
|
catch (InterruptedException e)
|
||||||
|
{
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code task} as a {@code Runnable} that completes {@code future} with its result or exception. */
|
||||||
|
private static <T> Runnable completing(Callable<T> task, CompletableFuture<T> future)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(task, "task");
|
||||||
|
|
||||||
|
return () -> {
|
||||||
|
try { future.complete(task.call()); }
|
||||||
|
catch (Throwable t) { future.completeExceptionally(t); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single daemon thread {@code zf-mod-<id>}. Every {@code Runnable} it runs through
|
||||||
|
* {@code execute}, {@code submit}, or {@code schedule...} is logged when it throws; the
|
||||||
|
* exception still reaches the task's future.
|
||||||
|
*/
|
||||||
|
private static final class ModThreadExecutor extends ScheduledThreadPoolExecutor
|
||||||
|
{
|
||||||
|
private final System.Logger logger;
|
||||||
|
|
||||||
|
/** The executor's thread, set when the thread is created. */
|
||||||
|
private volatile @Nullable Thread thread;
|
||||||
|
|
||||||
|
private ModThreadExecutor(String id, System.Logger logger)
|
||||||
|
{
|
||||||
|
super(1);
|
||||||
|
|
||||||
|
this.logger = logger;
|
||||||
|
|
||||||
|
this.setThreadFactory(task -> {
|
||||||
|
Thread created = new Thread(task, "zf-mod-" + id);
|
||||||
|
created.setDaemon(true);
|
||||||
|
|
||||||
|
this.thread = created;
|
||||||
|
return created;
|
||||||
|
});
|
||||||
|
this.setRemoveOnCancelPolicy(true);
|
||||||
|
this.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
|
||||||
|
this.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// execute() and submit(Runnable) go through schedule(Runnable, ...).
|
||||||
|
@Override
|
||||||
|
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return super.schedule(this.logged(command), delay, unit); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return super.scheduleAtFixedRate(this.logged(command), initialDelay, period, unit); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return super.scheduleWithFixedDelay(this.logged(command), initialDelay, delay, unit); }
|
||||||
|
|
||||||
|
private Runnable logged(Runnable command)
|
||||||
|
{
|
||||||
|
return () -> {
|
||||||
|
try
|
||||||
|
{
|
||||||
|
command.run();
|
||||||
|
}
|
||||||
|
catch (RuntimeException | Error e)
|
||||||
|
{
|
||||||
|
this.logger.log(System.Logger.Level.ERROR, "A task on the mod thread threw.", e);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a mod sees of its {@link ModThreadExecutor}. */
|
||||||
|
private static final class ModThreadHandle implements ModThread
|
||||||
|
{
|
||||||
|
private final ModThreadExecutor executor;
|
||||||
|
|
||||||
|
private ModThreadHandle(ModThreadExecutor executor) { this.executor = executor; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void execute(Runnable task) { this.executor.execute(task); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> CompletableFuture<T> submit(Callable<T> task)
|
||||||
|
{
|
||||||
|
CompletableFuture<T> future = new CompletableFuture<>();
|
||||||
|
this.executor.execute(ModThreads.completing(task, future));
|
||||||
|
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ScheduledFuture<?> schedule(Runnable task, Duration delay) { return this.executor.schedule(task, delay.toNanos(), TimeUnit.NANOSECONDS); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Duration initialDelay, Duration period) { return this.executor.scheduleAtFixedRate(task, initialDelay.toNanos(), period.toNanos(), TimeUnit.NANOSECONDS); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Duration initialDelay, Duration delay) { return this.executor.scheduleWithFixedDelay(task, initialDelay.toNanos(), delay.toNanos(), TimeUnit.NANOSECONDS); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isModThread() { return Thread.currentThread() == this.executor.thread; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a mod sees of its virtual-thread executor. */
|
||||||
|
private static final class AsyncHandle implements AsyncExecutor
|
||||||
|
{
|
||||||
|
private final ExecutorService executor;
|
||||||
|
|
||||||
|
private AsyncHandle(ExecutorService executor) { this.executor = executor; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void execute(Runnable task) { this.executor.execute(task); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> CompletableFuture<T> submit(Callable<T> task)
|
||||||
|
{
|
||||||
|
CompletableFuture<T> future = new CompletableFuture<>();
|
||||||
|
this.executor.execute(ModThreads.completing(task, future));
|
||||||
|
|
||||||
|
return future;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* Threads and events of loaded mods: the main-thread queue, each mod's own threads, and the
|
||||||
|
* event bus.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.core.runtime;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.storage;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A stored column of a mod table.
|
||||||
|
*
|
||||||
|
* @param removed whether the column is no longer part of the record; it stays in the table with
|
||||||
|
* its data
|
||||||
|
*/
|
||||||
|
record Column(String name, Column.Kind kind, boolean nullable, boolean removed)
|
||||||
|
{
|
||||||
|
/** Java types a column can hold, with their SQLite type. */
|
||||||
|
enum Kind
|
||||||
|
{
|
||||||
|
STRING("TEXT"), LONG("INTEGER"), INT("INTEGER"), DOUBLE("REAL"), FLOAT("REAL"), BOOLEAN("INTEGER"),
|
||||||
|
BYTES("BLOB"), UUID("TEXT"), INSTANT("TEXT"), ENUM("TEXT");
|
||||||
|
|
||||||
|
private final String sqlType;
|
||||||
|
|
||||||
|
Kind(String sqlType) { this.sqlType = sqlType; }
|
||||||
|
|
||||||
|
String sqlType() { return this.sqlType; }
|
||||||
|
|
||||||
|
/** @throws StorageException for a type columns cannot have */
|
||||||
|
static Kind of(Class<?> type, String where)
|
||||||
|
{
|
||||||
|
return switch (type)
|
||||||
|
{
|
||||||
|
case Class<?> t when t == String.class -> Kind.STRING;
|
||||||
|
case Class<?> t when t == long.class || t == Long.class -> Kind.LONG;
|
||||||
|
case Class<?> t when t == int.class || t == Integer.class -> Kind.INT;
|
||||||
|
case Class<?> t when t == double.class || t == Double.class -> Kind.DOUBLE;
|
||||||
|
case Class<?> t when t == float.class || t == Float.class -> Kind.FLOAT;
|
||||||
|
case Class<?> t when t == boolean.class || t == Boolean.class -> Kind.BOOLEAN;
|
||||||
|
case Class<?> t when t == byte[].class -> Kind.BYTES;
|
||||||
|
case Class<?> t when t == java.util.UUID.class -> Kind.UUID;
|
||||||
|
case Class<?> t when t == Instant.class -> Kind.INSTANT;
|
||||||
|
case Class<?> t when t.isEnum() -> Kind.ENUM;
|
||||||
|
|
||||||
|
default -> throw new StorageException(where + " has the type '" + type.getName() + "', which tables cannot store.");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The column definition for {@code CREATE TABLE} and {@code ADD COLUMN}. Non-null columns default to 0, so rows written without them stay valid. */
|
||||||
|
String definition() { return SqlTable.quoted(this.name) + " " + this.kind.sqlType() + (this.nullable ? "" : " NOT NULL DEFAULT 0"); }
|
||||||
|
|
||||||
|
/** {@code name:kind:nullable[:removed]}, as stored in {@code forge__tables}. */
|
||||||
|
String encode() { return this.name + ":" + this.kind.name().toLowerCase(Locale.ROOT) + ":" + (this.nullable ? "null" : "notnull") + (this.removed ? ":removed" : ""); }
|
||||||
|
|
||||||
|
Column asRemoved() { return new Column(this.name, this.kind, this.nullable, true); }
|
||||||
|
|
||||||
|
/** Whether a value stored for {@code other} can be read as this column. */
|
||||||
|
boolean sameType(Column other) { return this.kind == other.kind && this.nullable == other.nullable; }
|
||||||
|
|
||||||
|
static String encode(List<Column> columns)
|
||||||
|
{
|
||||||
|
List<String> parts = new ArrayList<>();
|
||||||
|
for (Column column : columns) parts.add(column.encode());
|
||||||
|
|
||||||
|
return String.join(",", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
static List<Column> decode(String text)
|
||||||
|
{
|
||||||
|
List<Column> columns = new ArrayList<>();
|
||||||
|
if (text.isEmpty()) return columns;
|
||||||
|
|
||||||
|
for (String part : text.split(","))
|
||||||
|
{
|
||||||
|
String[] fields = part.split(":");
|
||||||
|
columns.add(new Column(fields[0], Kind.valueOf(fields[1].toUpperCase(Locale.ROOT)), fields[2].equals("null"), fields.length > 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.storage;
|
||||||
|
|
||||||
|
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.api.storage.TableDefinition;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The storage of one mod: its tables are named {@code <id>__<name>}, and their schemas are kept
|
||||||
|
* in {@code forge__tables}. Opening a table creates it, or compares the record with the stored
|
||||||
|
* schema:
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>a new nullable component is added as a column (existing rows read {@code null});</li>
|
||||||
|
* <li>a removed component keeps its column and data (logged once);</li>
|
||||||
|
* <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>
|
||||||
|
*/
|
||||||
|
public final class ModTables implements ModStorage
|
||||||
|
{
|
||||||
|
private static final int NAME_MAX_LENGTH = 32;
|
||||||
|
|
||||||
|
/** A stored schema. */
|
||||||
|
private record Schema(int version, List<Column> columns) {}
|
||||||
|
|
||||||
|
/** Work on one stored row; may throw {@link SQLException}. */
|
||||||
|
@FunctionalInterface
|
||||||
|
private interface RowAction
|
||||||
|
{
|
||||||
|
void accept(Row row) throws SQLException;
|
||||||
|
}
|
||||||
|
|
||||||
|
private final String id;
|
||||||
|
private final StorageDatabase database;
|
||||||
|
private final System.Logger logger;
|
||||||
|
|
||||||
|
public ModTables(String id, StorageDatabase database, System.Logger logger)
|
||||||
|
{
|
||||||
|
this.id = id;
|
||||||
|
this.database = database;
|
||||||
|
this.logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves the tables of every earlier id in {@code previousIds} to {@code id}, once per pair
|
||||||
|
* (recorded in {@code forge__migrations}). Nothing happens without a database file.
|
||||||
|
*
|
||||||
|
* @param installed ids of the installed mods
|
||||||
|
* @throws StorageException when an earlier id is installed, or {@code id} already has tables
|
||||||
|
* while an earlier id has some
|
||||||
|
*/
|
||||||
|
public static void adoptPreviousIds(StorageDatabase database, String id, List<String> previousIds, Collection<String> installed)
|
||||||
|
{
|
||||||
|
if (previousIds.isEmpty() || !database.exists()) return;
|
||||||
|
|
||||||
|
database.runTransaction(connection ->
|
||||||
|
{
|
||||||
|
for (String previous : previousIds)
|
||||||
|
{
|
||||||
|
if (ModTables.applied(connection, id, previous)) continue;
|
||||||
|
|
||||||
|
if (installed.contains(previous))
|
||||||
|
throw new StorageException("'" + id + "': 'previous_ids' contains '" + previous + "', which is installed as a mod.");
|
||||||
|
|
||||||
|
List<String> tables = ModTables.tableNames(connection, previous);
|
||||||
|
|
||||||
|
if (!tables.isEmpty() && !ModTables.tableNames(connection, id).isEmpty())
|
||||||
|
throw new StorageException("'" + id + "': cannot take over the tables of '" + previous + "' " + tables + ", because '" + id + "' already has tables.");
|
||||||
|
|
||||||
|
for (String table : tables)
|
||||||
|
{
|
||||||
|
ModTables.execute(connection, "ALTER TABLE " + SqlTable.quoted(previous + "__" + table) + " RENAME TO " + SqlTable.quoted(id + "__" + table));
|
||||||
|
ModTables.update(connection, "UPDATE forge__tables SET mod = ? WHERE mod = ? AND name = ?", id, previous, table);
|
||||||
|
}
|
||||||
|
|
||||||
|
ModTables.update(connection, "INSERT INTO forge__migrations (mod, previous, applied_at) VALUES (?, ?, ?)", id, previous, System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <R extends Record> Table<R> table(String name, Class<R> type) { return this.define(name, type).open(); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <R extends Record> TableDefinition<R> define(String name, Class<R> type)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(type, "type");
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void transaction(Runnable work) { this.database.runTransaction(connection -> work.run()); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T> T transaction(Supplier<T> work) { return this.database.transaction(connection -> work.get()); }
|
||||||
|
|
||||||
|
private final class Definition<R extends Record> implements TableDefinition<R>
|
||||||
|
{
|
||||||
|
private final String name;
|
||||||
|
private final Class<R> type;
|
||||||
|
private final Map<Integer, Function<Row, R>> migrations = new HashMap<>();
|
||||||
|
private int version = 1;
|
||||||
|
|
||||||
|
private Definition(String name, Class<R> type)
|
||||||
|
{
|
||||||
|
this.name = name;
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TableDefinition<R> version(int version)
|
||||||
|
{
|
||||||
|
if (version < 1) throw new IllegalArgumentException("The schema version must be at least 1, found " + version + ".");
|
||||||
|
|
||||||
|
this.version = version;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public TableDefinition<R> migrate(int from, Function<Row, R> migration)
|
||||||
|
{
|
||||||
|
this.migrations.put(from, Objects.requireNonNull(migration, "migration"));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Table<R> open()
|
||||||
|
{
|
||||||
|
RecordCodec<R> codec = RecordCodec.of(this.type);
|
||||||
|
String physical = ModTables.this.id + "__" + this.name;
|
||||||
|
|
||||||
|
ModTables.this.database.runTransaction(connection -> this.prepare(connection, codec, physical));
|
||||||
|
|
||||||
|
return new SqlTable<>(ModTables.this.database, codec, physical);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void prepare(Connection connection, RecordCodec<R> codec, String physical) throws SQLException
|
||||||
|
{
|
||||||
|
Schema stored = ModTables.this.schema(connection, this.name);
|
||||||
|
String table = "'" + ModTables.this.id + "' table '" + this.name + "'";
|
||||||
|
|
||||||
|
if (stored == null)
|
||||||
|
{
|
||||||
|
ModTables.create(connection, physical, codec.columns());
|
||||||
|
ModTables.this.saveSchema(connection, this.name, this.version, codec.columns());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stored.version() > this.version)
|
||||||
|
throw new StorageException(table + " has schema version " + stored.version() + ", newer than the mod's " + this.version + ".");
|
||||||
|
|
||||||
|
if (stored.version() < this.version)
|
||||||
|
{
|
||||||
|
this.migrate(connection, codec, physical, stored, table);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Column> columns = new ArrayList<>(stored.columns());
|
||||||
|
List<String> problems = new ArrayList<>();
|
||||||
|
|
||||||
|
for (Column wanted : codec.columns())
|
||||||
|
{
|
||||||
|
Column existing = columns.stream().filter(column -> column.name().equals(wanted.name())).findFirst().orElse(null);
|
||||||
|
|
||||||
|
if (existing == null && wanted.nullable())
|
||||||
|
{
|
||||||
|
ModTables.execute(connection, "ALTER TABLE " + SqlTable.quoted(physical) + " ADD COLUMN " + wanted.definition());
|
||||||
|
columns.add(wanted);
|
||||||
|
}
|
||||||
|
else if (existing == null)
|
||||||
|
{
|
||||||
|
problems.add("new column '" + wanted.name() + "' cannot be null, so existing rows need a value");
|
||||||
|
}
|
||||||
|
else if (!existing.sameType(wanted))
|
||||||
|
{
|
||||||
|
problems.add("column '" + wanted.name() + "' changed from " + existing.encode() + " to " + wanted.encode());
|
||||||
|
}
|
||||||
|
else if (existing.removed())
|
||||||
|
{
|
||||||
|
columns.set(columns.indexOf(existing), wanted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!problems.isEmpty())
|
||||||
|
throw new StorageException(table + " does not match '" + this.type.getSimpleName() + "': " + String.join("; ", problems) + ". Raise its version and add a migration from version " + stored.version() + ".");
|
||||||
|
|
||||||
|
for (int i = 0; i < columns.size(); i++)
|
||||||
|
{
|
||||||
|
Column column = columns.get(i);
|
||||||
|
boolean inUse = codec.columns().stream().anyMatch(wanted -> wanted.name().equals(column.name()));
|
||||||
|
|
||||||
|
if (!inUse && !column.removed())
|
||||||
|
{
|
||||||
|
columns.set(i, column.asRemoved());
|
||||||
|
ModTables.this.logger.log(System.Logger.Level.WARNING, table + ": column '" + column.name() + "' is no longer in '" + this.type.getSimpleName() + "'; its data stays in the table.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ModTables.this.saveSchema(connection, this.name, this.version, columns);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rebuilds the table: every row through the migration from the stored version. */
|
||||||
|
private void migrate(Connection connection, RecordCodec<R> codec, String physical, Schema stored, String table) throws SQLException
|
||||||
|
{
|
||||||
|
Function<Row, R> migration = this.migrations.get(stored.version());
|
||||||
|
|
||||||
|
if (migration == null)
|
||||||
|
throw new StorageException(table + " has schema version " + stored.version() + ", the mod declares " + this.version + " but no migration from " + stored.version() + ".");
|
||||||
|
|
||||||
|
String rebuilt = physical + "__migrating";
|
||||||
|
SqlTable<R> target = new SqlTable<>(ModTables.this.database, codec, rebuilt);
|
||||||
|
|
||||||
|
ModTables.execute(connection, "DROP TABLE IF EXISTS " + SqlTable.quoted(rebuilt));
|
||||||
|
ModTables.create(connection, rebuilt, codec.columns());
|
||||||
|
|
||||||
|
int migrated = ModTables.forEachRow(connection, physical, row ->
|
||||||
|
{
|
||||||
|
R record;
|
||||||
|
|
||||||
|
try { record = Objects.requireNonNull(migration.apply(row), "migration result"); }
|
||||||
|
catch (RuntimeException e) { throw new StorageException(table + ": the migration from version " + stored.version() + " failed for row '" + row.key() + "': " + e, e); }
|
||||||
|
|
||||||
|
target.set(row.key(), record);
|
||||||
|
});
|
||||||
|
|
||||||
|
ModTables.execute(connection, "DROP TABLE " + SqlTable.quoted(physical));
|
||||||
|
ModTables.execute(connection, "ALTER TABLE " + SqlTable.quoted(rebuilt) + " RENAME TO " + SqlTable.quoted(physical));
|
||||||
|
ModTables.this.saveSchema(connection, this.name, this.version, codec.columns());
|
||||||
|
|
||||||
|
ModTables.this.logger.log(System.Logger.Level.INFO, table + ": migrated " + migrated + " row(s) from schema version " + stored.version() + " to " + this.version + ".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Schema schema(Connection connection, String name) throws SQLException
|
||||||
|
{
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT version, columns FROM forge__tables WHERE mod = ? AND name = ?"))
|
||||||
|
{
|
||||||
|
statement.setString(1, this.id);
|
||||||
|
statement.setString(2, name);
|
||||||
|
|
||||||
|
try (ResultSet rows = statement.executeQuery()) { return rows.next() ? new Schema(rows.getInt(1), Column.decode(rows.getString(2))) : null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void saveSchema(Connection connection, String name, int version, List<Column> columns) throws SQLException
|
||||||
|
{
|
||||||
|
ModTables.update(
|
||||||
|
connection,
|
||||||
|
"INSERT INTO forge__tables (mod, name, version, columns) VALUES (?, ?, ?, ?) ON CONFLICT (mod, name) DO UPDATE SET version = excluded.version, columns = excluded.columns",
|
||||||
|
this.id, name, version, Column.encode(columns)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void create(Connection connection, String physical, List<Column> columns) throws SQLException
|
||||||
|
{
|
||||||
|
String definitions = columns.stream().map(column -> ", " + column.definition()).collect(Collectors.joining());
|
||||||
|
ModTables.execute(connection, "CREATE TABLE " + SqlTable.quoted(physical) + " (" + SqlTable.quoted(SqlTable.KEY) + " TEXT PRIMARY KEY NOT NULL" + definitions + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calls {@code action} for every row of {@code physical} with all its columns, sorted by key,
|
||||||
|
* reading one row at a time.
|
||||||
|
*
|
||||||
|
* @return the number of rows
|
||||||
|
*/
|
||||||
|
private static int forEachRow(Connection connection, String physical, RowAction action) throws SQLException
|
||||||
|
{
|
||||||
|
int count = 0;
|
||||||
|
|
||||||
|
try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM " + SqlTable.quoted(physical) + " ORDER BY " + SqlTable.quoted(SqlTable.KEY)))
|
||||||
|
{
|
||||||
|
ResultSetMetaData meta = result.getMetaData();
|
||||||
|
|
||||||
|
while (result.next())
|
||||||
|
{
|
||||||
|
Map<String, @Nullable Object> values = new LinkedHashMap<>();
|
||||||
|
String key = "";
|
||||||
|
|
||||||
|
for (int i = 1; i <= meta.getColumnCount(); i++)
|
||||||
|
{
|
||||||
|
String column = meta.getColumnName(i);
|
||||||
|
Object value = result.getObject(i);
|
||||||
|
|
||||||
|
if (column.equals(SqlTable.KEY)) key = String.valueOf(value);
|
||||||
|
else values.put(column, value instanceof Integer number ? Long.valueOf(number) : value);
|
||||||
|
}
|
||||||
|
|
||||||
|
action.accept(new StoredRow(key, values));
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> tableNames(Connection connection, String mod) throws SQLException
|
||||||
|
{
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT name FROM forge__tables WHERE mod = ? ORDER BY name"))
|
||||||
|
{
|
||||||
|
statement.setString(1, mod);
|
||||||
|
|
||||||
|
List<String> names = new ArrayList<>();
|
||||||
|
try (ResultSet rows = statement.executeQuery()) { while (rows.next()) names.add(rows.getString(1)); }
|
||||||
|
|
||||||
|
return names;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean applied(Connection connection, String id, String previous) throws SQLException
|
||||||
|
{
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM forge__migrations WHERE mod = ? AND previous = ?"))
|
||||||
|
{
|
||||||
|
statement.setString(1, id);
|
||||||
|
statement.setString(2, previous);
|
||||||
|
|
||||||
|
try (ResultSet rows = statement.executeQuery()) { return rows.next(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void execute(Connection connection, String sql) throws SQLException
|
||||||
|
{
|
||||||
|
try (Statement statement = connection.createStatement()) { statement.execute(sql); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void update(Connection connection, String sql, Object... parameters) throws SQLException
|
||||||
|
{
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement(sql))
|
||||||
|
{
|
||||||
|
for (int i = 0; i < parameters.length; i++) statement.setObject(i + 1, parameters[i]);
|
||||||
|
|
||||||
|
statement.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.storage;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||||
|
import dev.overlord.zomboidforge.core.config.RecordBinder;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.lang.invoke.MethodHandle;
|
||||||
|
import java.lang.invoke.MethodHandles;
|
||||||
|
import java.lang.invoke.MethodType;
|
||||||
|
import java.lang.reflect.RecordComponent;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
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.
|
||||||
|
*
|
||||||
|
* <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
|
||||||
|
* {@code BLOB}.
|
||||||
|
*/
|
||||||
|
final class RecordCodec<R extends Record>
|
||||||
|
{
|
||||||
|
/** Same rule as mod ids: lowercase, digits, single underscores. */
|
||||||
|
static final Pattern NAME = Pattern.compile("[a-z][a-z0-9]*(_[a-z0-9]+)*");
|
||||||
|
|
||||||
|
private final Class<R> type;
|
||||||
|
private final List<Column> columns;
|
||||||
|
private final Class<?>[] types;
|
||||||
|
private final MethodHandle[] accessors;
|
||||||
|
private final MethodHandle constructor;
|
||||||
|
|
||||||
|
private RecordCodec(Class<R> type, List<Column> columns, Class<?>[] types, MethodHandle[] accessors, MethodHandle constructor)
|
||||||
|
{
|
||||||
|
this.type = type;
|
||||||
|
this.columns = List.copyOf(columns);
|
||||||
|
this.types = types;
|
||||||
|
this.accessors = accessors;
|
||||||
|
this.constructor = constructor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @throws StorageException when a component has a name or type tables cannot store */
|
||||||
|
static <R extends Record> RecordCodec<R> of(Class<R> type)
|
||||||
|
{
|
||||||
|
RecordComponent[] components = type.getRecordComponents();
|
||||||
|
List<Column> columns = new ArrayList<>();
|
||||||
|
Class<?>[] types = new Class<?>[components.length];
|
||||||
|
MethodHandle[] accessors = new MethodHandle[components.length];
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(type, MethodHandles.lookup());
|
||||||
|
|
||||||
|
for (int i = 0; i < components.length; i++)
|
||||||
|
{
|
||||||
|
RecordComponent component = components[i];
|
||||||
|
String name = RecordBinder.key(component.getName());
|
||||||
|
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.");
|
||||||
|
|
||||||
|
types[i] = component.getType();
|
||||||
|
accessors[i] = lookup.unreflect(component.getAccessor());
|
||||||
|
columns.add(new Column(name, Column.Kind.of(types[i], where), !types[i].isPrimitive(), false));
|
||||||
|
}
|
||||||
|
|
||||||
|
MethodHandle constructor = lookup.findConstructor(type, MethodType.methodType(void.class, types));
|
||||||
|
return new RecordCodec<>(type, columns, types, accessors, constructor);
|
||||||
|
}
|
||||||
|
catch (ReflectiveOperationException e)
|
||||||
|
{
|
||||||
|
throw new StorageException("Cannot access record '" + type.getName() + "': " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Column> columns() { return this.columns; }
|
||||||
|
|
||||||
|
/** Binds the components of {@code record} to the parameters from {@code first} on. */
|
||||||
|
void bind(PreparedStatement statement, int first, R record) throws SQLException
|
||||||
|
{
|
||||||
|
for (int i = 0; i < this.accessors.length; i++) statement.setObject(first + i, RecordCodec.stored(this.columns.get(i).kind(), this.component(record, i)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A record from the columns of {@code rows} from {@code first} on, in component order. */
|
||||||
|
R read(ResultSet rows, int first) throws SQLException
|
||||||
|
{
|
||||||
|
@Nullable Object[] arguments = new Object[this.types.length];
|
||||||
|
|
||||||
|
for (int i = 0; i < this.types.length; i++)
|
||||||
|
{
|
||||||
|
Column column = this.columns.get(i);
|
||||||
|
Object stored = rows.getObject(first + i);
|
||||||
|
|
||||||
|
if (stored == null && !column.nullable())
|
||||||
|
throw new StorageException("Column '" + column.name() + "' of '" + this.type.getSimpleName() + "' is null in the database.");
|
||||||
|
|
||||||
|
try { arguments[i] = stored == null ? null : RecordCodec.value(column.kind(), this.types[i], stored); }
|
||||||
|
catch (RuntimeException e) { throw new StorageException("Column '" + column.name() + "' of '" + this.type.getSimpleName() + "' holds '" + stored + "', which is not a valid '" + this.types[i].getSimpleName() + "': " + e, e); }
|
||||||
|
}
|
||||||
|
|
||||||
|
try { return this.type.cast(this.constructor.invokeWithArguments(arguments)); }
|
||||||
|
catch (Throwable t) { throw new StorageException("'" + this.type.getSimpleName() + "' rejected the stored values: " + t, t); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private @Nullable Object component(R record, int index)
|
||||||
|
{
|
||||||
|
try { return this.accessors[index].invoke(record); }
|
||||||
|
catch (Throwable t) { throw new StorageException("Cannot read '" + this.columns.get(index).name() + "' of '" + this.type.getSimpleName() + "': " + t, t); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@code value} in its stored form. */
|
||||||
|
static @Nullable Object stored(Column.Kind kind, @Nullable Object value)
|
||||||
|
{
|
||||||
|
if (value == null) return null;
|
||||||
|
|
||||||
|
return switch (kind)
|
||||||
|
{
|
||||||
|
case STRING, LONG, DOUBLE, BYTES -> value;
|
||||||
|
case INT -> ((Integer) value).longValue();
|
||||||
|
case FLOAT -> ((Float) value).doubleValue();
|
||||||
|
case BOOLEAN -> (Boolean) value ? 1L : 0L;
|
||||||
|
case UUID, INSTANT -> value.toString();
|
||||||
|
case ENUM -> ((Enum<?>) value).name();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A stored value converted back to {@code type}. */
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
private static Object value(Column.Kind kind, Class<?> type, Object stored)
|
||||||
|
{
|
||||||
|
return switch (kind)
|
||||||
|
{
|
||||||
|
case STRING, BYTES -> stored;
|
||||||
|
case LONG -> ((Number) stored).longValue();
|
||||||
|
case INT -> ((Number) stored).intValue();
|
||||||
|
case DOUBLE -> ((Number) stored).doubleValue();
|
||||||
|
case FLOAT -> ((Number) stored).floatValue();
|
||||||
|
case BOOLEAN -> ((Number) stored).longValue() != 0;
|
||||||
|
case UUID -> UUID.fromString((String) stored);
|
||||||
|
case INSTANT -> Instant.parse((String) stored);
|
||||||
|
case ENUM -> Enum.valueOf((Class) type, (String) stored);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() { return this.type.getSimpleName() + Arrays.toString(this.columns.toArray()); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.storage;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.storage.Table;
|
||||||
|
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.function.UnaryOperator;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A mod table: {@code "<id>__<name>"} with the key column {@code _key} and one column per record
|
||||||
|
* component. The key column starts with an underscore, so no component can have its name.
|
||||||
|
*/
|
||||||
|
// SQL strings contain only identifiers checked by quoted(); values are bound as parameters.
|
||||||
|
@SuppressWarnings("SqlSourceToSinkFlow")
|
||||||
|
final class SqlTable<R extends Record> implements Table<R>
|
||||||
|
{
|
||||||
|
/** Name of the key column. */
|
||||||
|
static final String KEY = "_key";
|
||||||
|
|
||||||
|
private static final Pattern IDENTIFIER = Pattern.compile("[a-z_][a-z0-9_]*");
|
||||||
|
|
||||||
|
/** Keys per statement in {@link #getAll} and {@link #deleteAll}. */
|
||||||
|
private static final int BATCH = 500;
|
||||||
|
|
||||||
|
private final StorageDatabase database;
|
||||||
|
private final RecordCodec<R> codec;
|
||||||
|
private final String physical;
|
||||||
|
private final String columns;
|
||||||
|
private final String upsert;
|
||||||
|
|
||||||
|
/** @param physical the table's name in the database, {@code <id>__<name>} */
|
||||||
|
SqlTable(StorageDatabase database, RecordCodec<R> codec, String physical)
|
||||||
|
{
|
||||||
|
this.database = database;
|
||||||
|
this.codec = codec;
|
||||||
|
this.physical = SqlTable.quoted(physical);
|
||||||
|
this.columns = SqlTable.quoted(SqlTable.KEY) + codec.columns().stream().map(column -> ", " + SqlTable.quoted(column.name())).collect(Collectors.joining());
|
||||||
|
this.upsert = SqlTable.upsert(this.physical, codec.columns());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void set(String key, R value)
|
||||||
|
{
|
||||||
|
Objects.requireNonNull(key, "key");
|
||||||
|
Objects.requireNonNull(value, "value");
|
||||||
|
|
||||||
|
this.database.call(connection -> {
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement(this.upsert))
|
||||||
|
{
|
||||||
|
statement.setString(1, key);
|
||||||
|
this.codec.bind(statement, 2, value);
|
||||||
|
|
||||||
|
return statement.executeUpdate();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setAll(Map<String, R> values)
|
||||||
|
{
|
||||||
|
this.database.transaction(connection -> {
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement(this.upsert))
|
||||||
|
{
|
||||||
|
for (Map.Entry<String, R> entry : values.entrySet())
|
||||||
|
{
|
||||||
|
statement.setString(1, Objects.requireNonNull(entry.getKey(), "key"));
|
||||||
|
this.codec.bind(statement, 2, Objects.requireNonNull(entry.getValue(), "value"));
|
||||||
|
statement.addBatch();
|
||||||
|
}
|
||||||
|
|
||||||
|
return statement.executeBatch();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<R> get(String key)
|
||||||
|
{
|
||||||
|
return this.database.call(connection -> {
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT " + this.columns + " FROM " + this.physical + " WHERE " + SqlTable.quoted(SqlTable.KEY) + " = ?"))
|
||||||
|
{
|
||||||
|
statement.setString(1, key);
|
||||||
|
|
||||||
|
try (ResultSet rows = statement.executeQuery()) { return rows.next() ? Optional.of(this.codec.read(rows, 2)) : Optional.empty(); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, R> getAll(Collection<String> keys)
|
||||||
|
{
|
||||||
|
Map<String, R> found = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
this.database.call(connection -> {
|
||||||
|
for (List<String> batch : SqlTable.batches(keys))
|
||||||
|
{
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT " + this.columns + " FROM " + this.physical + " WHERE " + SqlTable.quoted(SqlTable.KEY) + " IN (" + SqlTable.placeholders(batch.size()) + ")"))
|
||||||
|
{
|
||||||
|
for (int i = 0; i < batch.size(); i++) statement.setString(i + 1, batch.get(i));
|
||||||
|
|
||||||
|
try (ResultSet rows = statement.executeQuery()) { while (rows.next()) found.put(rows.getString(1), this.codec.read(rows, 2)); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return found;
|
||||||
|
});
|
||||||
|
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean contains(String key)
|
||||||
|
{
|
||||||
|
return this.database.call(connection -> {
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM " + this.physical + " WHERE " + SqlTable.quoted(SqlTable.KEY) + " = ?"))
|
||||||
|
{
|
||||||
|
statement.setString(1, key);
|
||||||
|
|
||||||
|
try (ResultSet rows = statement.executeQuery()) { return rows.next(); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean delete(String key) { return this.deleteAll(List.of(key)) > 0; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int deleteAll(Collection<String> keys)
|
||||||
|
{
|
||||||
|
return this.database.transaction(connection -> {
|
||||||
|
int deleted = 0;
|
||||||
|
|
||||||
|
for (List<String> batch : SqlTable.batches(keys))
|
||||||
|
{
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("DELETE FROM " + this.physical + " WHERE " + SqlTable.quoted(SqlTable.KEY) + " IN (" + SqlTable.placeholders(batch.size()) + ")"))
|
||||||
|
{
|
||||||
|
for (int i = 0; i < batch.size(); i++) statement.setString(i + 1, batch.get(i));
|
||||||
|
|
||||||
|
deleted += statement.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return deleted;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> keys()
|
||||||
|
{
|
||||||
|
return this.database.call(connection -> {
|
||||||
|
List<String> keys = new ArrayList<>();
|
||||||
|
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT " + SqlTable.quoted(SqlTable.KEY) + " FROM " + this.physical + " ORDER BY 1");
|
||||||
|
ResultSet rows = statement.executeQuery())
|
||||||
|
{
|
||||||
|
while (rows.next()) keys.add(rows.getString(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
return keys;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void forEach(BiConsumer<String, R> action)
|
||||||
|
{
|
||||||
|
this.database.run(connection ->
|
||||||
|
{
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT " + this.columns + " FROM " + this.physical + " ORDER BY 1");
|
||||||
|
ResultSet rows = statement.executeQuery())
|
||||||
|
{
|
||||||
|
while (rows.next()) action.accept(rows.getString(1), this.codec.read(rows, 2));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long count()
|
||||||
|
{
|
||||||
|
return this.database.call(connection -> {
|
||||||
|
try (PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM " + this.physical);
|
||||||
|
ResultSet rows = statement.executeQuery())
|
||||||
|
{
|
||||||
|
rows.next();
|
||||||
|
return rows.getLong(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public R update(String key, UnaryOperator<R> change, Supplier<R> initial)
|
||||||
|
{
|
||||||
|
return this.database.transaction(connection -> {
|
||||||
|
R updated = Objects.requireNonNull(change.apply(this.get(key).orElseGet(initial)), "update result");
|
||||||
|
this.set(key, updated);
|
||||||
|
|
||||||
|
return updated;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code name} as a quoted SQL identifier. Table and column names are built from mod ids,
|
||||||
|
* table names, and component names, which all consist of lowercase letters, digits, and
|
||||||
|
* underscores; anything else is rejected, so no identifier can change a statement.
|
||||||
|
*/
|
||||||
|
static String quoted(String name)
|
||||||
|
{
|
||||||
|
if (!SqlTable.IDENTIFIER.matcher(name).matches()) throw new IllegalArgumentException("Not a valid SQL identifier: '" + name + "'.");
|
||||||
|
|
||||||
|
return "\"" + name + "\"";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param physical the quoted table name */
|
||||||
|
private static String upsert(String physical, List<Column> columns)
|
||||||
|
{
|
||||||
|
String names = columns.stream().map(column -> ", " + SqlTable.quoted(column.name())).collect(Collectors.joining());
|
||||||
|
String placeholders = ", ?".repeat(columns.size());
|
||||||
|
String updates = columns.stream().map(column -> SqlTable.quoted(column.name()) + " = excluded." + SqlTable.quoted(column.name())).collect(Collectors.joining(", "));
|
||||||
|
String conflict = columns.isEmpty() ? "DO NOTHING" : "DO UPDATE SET " + updates;
|
||||||
|
|
||||||
|
return "INSERT INTO " + physical + " (" + SqlTable.quoted(SqlTable.KEY) + names + ") VALUES (?" + placeholders + ") ON CONFLICT (" + SqlTable.quoted(SqlTable.KEY) + ") " + conflict;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String placeholders(int count) { return String.join(", ", Collections.nCopies(count, "?")); }
|
||||||
|
|
||||||
|
private static List<List<String>> batches(Collection<String> keys)
|
||||||
|
{
|
||||||
|
List<String> all = List.copyOf(keys);
|
||||||
|
List<List<String>> batches = new ArrayList<>();
|
||||||
|
|
||||||
|
for (int start = 0; start < all.size(); start += SqlTable.BATCH) batches.add(all.subList(start, Math.min(all.size(), start + SqlTable.BATCH)));
|
||||||
|
|
||||||
|
return batches;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.storage;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Savepoint;
|
||||||
|
import java.sql.Statement;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code zomboidforge.db}: one SQLite connection in WAL mode, used by one thread at a time
|
||||||
|
* (a reentrant lock), opened on first use. A thread inside {@link #transaction} keeps the lock,
|
||||||
|
* so its writes and reads belong to the transaction; other threads wait.
|
||||||
|
*
|
||||||
|
* <p>Meta tables, owned by the reserved id {@code forge}:
|
||||||
|
* <ul>
|
||||||
|
* <li>{@code forge__tables(mod, name, version, columns)}: schema of every mod table;</li>
|
||||||
|
* <li>{@code forge__migrations(mod, previous, applied_at)}: applied {@code previous_ids}
|
||||||
|
* renames.</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public final class StorageDatabase implements AutoCloseable
|
||||||
|
{
|
||||||
|
/** File name, in the world's save folder. */
|
||||||
|
public static final String FILE = "zomboidforge.db";
|
||||||
|
|
||||||
|
/** Longest wait of a backup for the running storage operation. */
|
||||||
|
static final Duration BACKUP_WAIT = Duration.ofSeconds(10);
|
||||||
|
|
||||||
|
/** Work with the connection that has a result; may throw {@link SQLException}. */
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface Work<T>
|
||||||
|
{
|
||||||
|
T run(Connection connection) throws SQLException;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Work with the connection without a result; may throw {@link SQLException}. */
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface Action
|
||||||
|
{
|
||||||
|
void run(Connection connection) throws SQLException;
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Path file;
|
||||||
|
private final BooleanSupplier forbidden;
|
||||||
|
private final ReentrantLock lock = new ReentrantLock();
|
||||||
|
|
||||||
|
/** Guarded by {@link #lock}. */
|
||||||
|
private @Nullable Connection connection;
|
||||||
|
private int depth;
|
||||||
|
private boolean closed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param forbidden whether the calling thread must not use storage now (the main thread
|
||||||
|
* while the server runs)
|
||||||
|
*/
|
||||||
|
public StorageDatabase(Path file, BooleanSupplier forbidden)
|
||||||
|
{
|
||||||
|
this.file = file;
|
||||||
|
this.forbidden = forbidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the database file exists or is open. */
|
||||||
|
public boolean exists()
|
||||||
|
{
|
||||||
|
this.lock.lock();
|
||||||
|
try { return this.connection != null || Files.isRegularFile(this.file); }
|
||||||
|
finally { this.lock.unlock(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs {@code work} with the connection, holding the lock; inside a transaction when one is running on this thread. */
|
||||||
|
public <T> T call(Work<T> work)
|
||||||
|
{
|
||||||
|
this.checkCaller();
|
||||||
|
this.lock.lock();
|
||||||
|
|
||||||
|
try { return work.run(this.connection()); }
|
||||||
|
catch (SQLException e) { throw new StorageException("Storage error: " + e.getMessage(), e); }
|
||||||
|
finally { this.lock.unlock(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Like {@link #call}, for work without a result. */
|
||||||
|
public void run(Action action)
|
||||||
|
{
|
||||||
|
this.call(connection ->
|
||||||
|
{
|
||||||
|
action.run(connection);
|
||||||
|
return Boolean.TRUE;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Like {@link #transaction}, for work without a result. */
|
||||||
|
public void runTransaction(Action action)
|
||||||
|
{
|
||||||
|
this.transaction(connection ->
|
||||||
|
{
|
||||||
|
action.run(connection);
|
||||||
|
return Boolean.TRUE;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs {@code work} in a transaction. The outermost call on a thread commits when
|
||||||
|
* {@code work} returns and rolls back when it throws. A nested call runs inside a savepoint
|
||||||
|
* of the outer transaction: when its {@code work} throws, only its own writes are rolled
|
||||||
|
* back, also when the outer work catches the exception.
|
||||||
|
*/
|
||||||
|
public <T> T transaction(Work<T> work)
|
||||||
|
{
|
||||||
|
this.checkCaller();
|
||||||
|
this.lock.lock();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Connection connection = this.connection();
|
||||||
|
boolean outermost = this.depth == 0;
|
||||||
|
|
||||||
|
if (outermost) connection.setAutoCommit(false);
|
||||||
|
|
||||||
|
Savepoint savepoint = outermost ? null : connection.setSavepoint();
|
||||||
|
this.depth++;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
T result = work.run(connection);
|
||||||
|
|
||||||
|
if (savepoint == null) connection.commit();
|
||||||
|
else connection.releaseSavepoint(savepoint);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Throwable t)
|
||||||
|
{
|
||||||
|
StorageDatabase.rollback(connection, savepoint, t);
|
||||||
|
throw t;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
this.depth--;
|
||||||
|
if (outermost) connection.setAutoCommit(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (SQLException e)
|
||||||
|
{
|
||||||
|
throw new StorageException("Storage error: " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
this.lock.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blocks storage for a backup of the save folder: waits up to {@link #BACKUP_WAIT} for the
|
||||||
|
* running operation, writes the WAL into the database file
|
||||||
|
* ({@code PRAGMA wal_checkpoint(TRUNCATE)}), and keeps the lock until
|
||||||
|
* {@link #backupFinished()} on the same thread. Other threads' storage calls wait.
|
||||||
|
*
|
||||||
|
* <p>When the running operation takes longer, for example a transaction that waits for the
|
||||||
|
* thread making the backup, the backup runs without the lock and storage stays usable.
|
||||||
|
*
|
||||||
|
* @return a problem to log, or {@code null}
|
||||||
|
*/
|
||||||
|
public @Nullable String backupStarted() { return this.backupStarted(StorageDatabase.BACKUP_WAIT); }
|
||||||
|
|
||||||
|
@Nullable String backupStarted(Duration wait)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!this.lock.tryLock(wait.toMillis(), TimeUnit.MILLISECONDS))
|
||||||
|
return "Storage was busy for " + wait.toSeconds() + " s; the backup runs without pausing storage, so its copy of '" + StorageDatabase.FILE + "' may be incomplete.";
|
||||||
|
}
|
||||||
|
catch (InterruptedException e)
|
||||||
|
{
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
return "Interrupted while waiting for storage; the backup runs without pausing storage, so its copy of '" + StorageDatabase.FILE + "' may be incomplete.";
|
||||||
|
}
|
||||||
|
|
||||||
|
Connection connection = this.connection;
|
||||||
|
if (connection == null) return null;
|
||||||
|
|
||||||
|
try (Statement statement = connection.createStatement())
|
||||||
|
{
|
||||||
|
statement.execute("PRAGMA wal_checkpoint(TRUNCATE)");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (SQLException e)
|
||||||
|
{
|
||||||
|
return "Checkpoint before the backup failed: " + e.getMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Releases the lock taken by {@link #backupStarted()}. */
|
||||||
|
public void backupFinished()
|
||||||
|
{
|
||||||
|
if (this.lock.isHeldByCurrentThread()) this.lock.unlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Closes the connection; later calls throw. */
|
||||||
|
@Override
|
||||||
|
public void close()
|
||||||
|
{
|
||||||
|
this.lock.lock();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
this.closed = true;
|
||||||
|
|
||||||
|
Connection connection = this.connection;
|
||||||
|
this.connection = null;
|
||||||
|
|
||||||
|
if (connection != null) connection.close();
|
||||||
|
}
|
||||||
|
catch (SQLException e)
|
||||||
|
{
|
||||||
|
throw new StorageException("Cannot close '" + this.file + "': " + e.getMessage(), e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
this.lock.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void checkCaller()
|
||||||
|
{
|
||||||
|
if (this.forbidden.getAsBoolean())
|
||||||
|
throw new IllegalStateException("Storage cannot be used on the main thread while the server runs; use modThread() or async().");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The open connection; opens it and creates the meta tables on first use. Lock held. */
|
||||||
|
private Connection connection() throws SQLException
|
||||||
|
{
|
||||||
|
if (this.closed) throw new StorageException("Storage is closed: the server is stopping.");
|
||||||
|
|
||||||
|
Connection open = this.connection;
|
||||||
|
if (open != null) return open;
|
||||||
|
|
||||||
|
try { Files.createDirectories(this.file.toAbsolutePath().getParent()); }
|
||||||
|
catch (IOException e) { throw new StorageException("Cannot create the folder of '" + this.file + "': " + e.getMessage(), e); }
|
||||||
|
|
||||||
|
Connection connection = DriverManager.getConnection("jdbc:sqlite:" + this.file.toAbsolutePath());
|
||||||
|
|
||||||
|
try (Statement statement = connection.createStatement())
|
||||||
|
{
|
||||||
|
statement.execute("PRAGMA journal_mode = WAL");
|
||||||
|
statement.execute("PRAGMA synchronous = NORMAL");
|
||||||
|
statement.execute("PRAGMA busy_timeout = 5000");
|
||||||
|
statement.execute("CREATE TABLE IF NOT EXISTS forge__tables (mod TEXT NOT NULL, name TEXT NOT NULL, version INTEGER NOT NULL, columns TEXT NOT NULL, PRIMARY KEY (mod, name))");
|
||||||
|
statement.execute("CREATE TABLE IF NOT EXISTS forge__migrations (mod TEXT NOT NULL, previous TEXT NOT NULL, applied_at INTEGER NOT NULL, PRIMARY KEY (mod, previous))");
|
||||||
|
}
|
||||||
|
catch (SQLException e)
|
||||||
|
{
|
||||||
|
connection.close();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.connection = connection;
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rolls back the transaction, or only to {@code savepoint} (and releases it) when one is given. */
|
||||||
|
private static void rollback(Connection connection, @Nullable Savepoint savepoint, Throwable cause)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (savepoint == null) {
|
||||||
|
connection.rollback();
|
||||||
|
} else {
|
||||||
|
connection.rollback(savepoint);
|
||||||
|
connection.releaseSavepoint(savepoint);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (SQLException e)
|
||||||
|
{
|
||||||
|
cause.addSuppressed(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.storage;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.storage.Row;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
/** A row as read for a migration: the key and every stored column. */
|
||||||
|
final class StoredRow implements Row
|
||||||
|
{
|
||||||
|
private final String key;
|
||||||
|
private final Map<String, @Nullable Object> values;
|
||||||
|
|
||||||
|
StoredRow(String key, Map<String, @Nullable Object> values)
|
||||||
|
{
|
||||||
|
this.key = key;
|
||||||
|
this.values = Collections.unmodifiableMap(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String key() { return this.key; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<String> columns() { return this.values.keySet(); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public @Nullable Object get(String column)
|
||||||
|
{
|
||||||
|
if (!this.values.containsKey(column)) throw new IllegalArgumentException("No column '" + column + "'; stored columns: " + this.values.keySet() + ".");
|
||||||
|
|
||||||
|
return this.values.get(column);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public @Nullable String getString(String column) { return (String) this.get(column); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long getLong(String column) { return this.number(column).longValue(); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public double getDouble(String column) { return this.number(column).doubleValue(); }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean getBoolean(String column) { return this.number(column).longValue() != 0; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte @Nullable [] getBytes(String column) { return (byte[]) this.get(column); }
|
||||||
|
|
||||||
|
private Number number(String column)
|
||||||
|
{
|
||||||
|
Object value = this.get(column);
|
||||||
|
if (value == null) throw new IllegalStateException("Column '" + column + "' of row '" + this.key + "' is null.");
|
||||||
|
|
||||||
|
return (Number) value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* Mod storage: {@code zomboidforge.db} next to the world's save, record tables per mod, schema
|
||||||
|
* checks and migrations.
|
||||||
|
*
|
||||||
|
* @noinspection UnstableApiUsage, RedundantSuppression
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
package dev.overlord.zomboidforge.core.storage;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.NotNullByDefault;
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
package dev.overlord.zomboidforge.core;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.Event;
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModLoadException;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.ModVersion;
|
||||||
|
import dev.overlord.zomboidforge.core.mods.TestMods;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import testmods.ContextMod;
|
||||||
|
import testmods.ErrorMod;
|
||||||
|
import testmods.Recorder;
|
||||||
|
import testmods.ThreadMod;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
import java.util.function.BooleanSupplier;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
class ForgeTest
|
||||||
|
{
|
||||||
|
private static final GameVersion GAME = GameVersion.parse("42.21.0");
|
||||||
|
|
||||||
|
/** Mods that call {@link Recorder} use the fake game jar, so they declare {@code game}. */
|
||||||
|
private static final String USES_GAME = "game = [\"42\"]\n";
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path directory;
|
||||||
|
|
||||||
|
private Path mods;
|
||||||
|
private Path gameJar;
|
||||||
|
private Path storageFile;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws IOException
|
||||||
|
{
|
||||||
|
this.mods = Files.createDirectories(this.directory.resolve("mods"));
|
||||||
|
this.gameJar = TestMods.gameJar(this.directory.resolve("projectzomboid.jar"));
|
||||||
|
|
||||||
|
this.storageFile = this.directory.resolve("Saves").resolve("Multiplayer").resolve("test").resolve("zomboidforge.db");
|
||||||
|
|
||||||
|
Recorder.EVENTS.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Forge forge() { return new Forge(this.directory, ModVersion.parse("0.3.0")); }
|
||||||
|
|
||||||
|
private Forge load() throws ModLoadException
|
||||||
|
{
|
||||||
|
Forge forge = this.forge();
|
||||||
|
forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile);
|
||||||
|
|
||||||
|
return forge;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@link ContextMod} and its settings record, packaged as the mod {@code context}. */
|
||||||
|
private void contextMod(String extra, @Nullable String defaultConfig) throws IOException
|
||||||
|
{
|
||||||
|
TestMods.folder(this.mods, "context", TestMods.toml("context", ContextMod.class.getName(), extra), defaultConfig, Map.of(
|
||||||
|
"testmods/ContextMod", TestMods.classFile(ContextMod.class),
|
||||||
|
"testmods/ContextMod$Settings", TestMods.classFile(ContextMod.Settings.class)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loadsStartsAndStopsModsInDependencyOrder() throws Exception
|
||||||
|
{
|
||||||
|
TestMods.folder(this.mods, "shop", TestMods.toml("shop", "shop.ShopMod", ForgeTest.USES_GAME + "[dependencies]\neconomy = \"1.0\"\n"), Map.of(
|
||||||
|
"shop/ShopMod", TestMods.modClass("shop/ShopMod", "shop", "economy/Accounts", false)
|
||||||
|
));
|
||||||
|
TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ForgeTest.USES_GAME), Map.of(
|
||||||
|
"economy/EconomyMod", TestMods.modClass("economy/EconomyMod", "economy", null, false),
|
||||||
|
"economy/Accounts", TestMods.pingClass("economy/Accounts")
|
||||||
|
));
|
||||||
|
|
||||||
|
Forge forge = this.load();
|
||||||
|
assertEquals(Lifecycle.Phase.LOADED, forge.phase());
|
||||||
|
assertEquals(List.of("economy", "shop"), forge.mods().stream().map(mod -> mod.descriptor().id()).toList());
|
||||||
|
|
||||||
|
forge.started();
|
||||||
|
forge.stopping();
|
||||||
|
forge.stopping();
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of(
|
||||||
|
"economy:new", "economy:onLoad",
|
||||||
|
"shop:new", "economy/Accounts:ping", "shop:onLoad",
|
||||||
|
"economy:onServerStarted", "shop:onServerStarted",
|
||||||
|
"shop:onStopping", "economy:onStopping"
|
||||||
|
),
|
||||||
|
Recorder.EVENTS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modsSeeTheirContextAndSettingsInTheConstructor() throws Exception
|
||||||
|
{
|
||||||
|
this.contextMod("", """
|
||||||
|
greeting = "default"
|
||||||
|
limit = 5
|
||||||
|
|
||||||
|
[prices]
|
||||||
|
apple = 3
|
||||||
|
""");
|
||||||
|
Files.writeString(this.mods.resolve("context").resolve("config.toml"), "greeting = \"hi\"\n");
|
||||||
|
|
||||||
|
Object mod = this.load().mods().getFirst().mod();
|
||||||
|
|
||||||
|
assertNotSame(ContextMod.class, mod.getClass(), "the mod class comes from the mod's jar");
|
||||||
|
assertEquals("context", ForgeTest.field(mod, "idInConstructor"));
|
||||||
|
assertEquals(ForgeTest.GAME, ForgeTest.field(mod, "gameInConstructor"));
|
||||||
|
assertEquals(this.mods.resolve("context"), ForgeTest.field(mod, "directoryInConstructor"));
|
||||||
|
assertEquals("Settings[greeting=hi, limit=5, extra=Optional.empty, prices={apple=3}]", ForgeTest.field(mod, "settings").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void writesTheDefaultSettingsWhenTheFolderHasNone() throws Exception
|
||||||
|
{
|
||||||
|
String defaults = "greeting = \"default\"\nlimit = 5\n[prices]\n";
|
||||||
|
this.contextMod("", defaults);
|
||||||
|
|
||||||
|
this.load();
|
||||||
|
|
||||||
|
assertEquals(defaults, Files.readString(this.mods.resolve("context").resolve("config.toml")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failsWhenTheSettingsDoNotMatchTheRecord() throws IOException
|
||||||
|
{
|
||||||
|
this.contextMod("", "greeting = 7\n");
|
||||||
|
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, this::load);
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of("'context': the constructor of 'testmods.ContextMod' threw java.lang.IllegalStateException: config.toml does not match 'Settings': 'greeting' must be a string, found 7. 'limit' is missing. 'prices' is missing."),
|
||||||
|
e.problems()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void skipsDisabledModsAndFailsTheirDependents() throws Exception
|
||||||
|
{
|
||||||
|
this.contextMod("", null);
|
||||||
|
Files.writeString(this.mods.resolve("context").resolve("config.toml"), "[forge]\nenabled = false\n");
|
||||||
|
|
||||||
|
Forge forge = this.load();
|
||||||
|
assertTrue(forge.mods().isEmpty());
|
||||||
|
|
||||||
|
TestMods.folder(this.mods, "needs", TestMods.toml("needs", "needs.Mod", "[dependencies]\ncontext = \"1.0\"\n"), Map.of());
|
||||||
|
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, this::load);
|
||||||
|
assertEquals(List.of("'needs': requires 'context', which is disabled in its config.toml."), e.problems());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modsCannotBeCreatedOutsideZomboidForge()
|
||||||
|
{
|
||||||
|
IllegalStateException e = assertThrows(IllegalStateException.class, ContextMod::new);
|
||||||
|
|
||||||
|
assertEquals("'" + ContextMod.class.getName() + "' can only be created by ZomboidForge.", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loadsNothingWithoutModsFolder() throws Exception
|
||||||
|
{
|
||||||
|
Files.delete(this.mods);
|
||||||
|
|
||||||
|
Forge forge = this.load();
|
||||||
|
|
||||||
|
assertTrue(forge.mods().isEmpty());
|
||||||
|
assertEquals(Lifecycle.Phase.LOADED, forge.phase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failsWhenOnLoadThrows() throws IOException
|
||||||
|
{
|
||||||
|
TestMods.folder(this.mods, "broken", TestMods.toml("broken", "broken.BrokenMod", ForgeTest.USES_GAME), Map.of(
|
||||||
|
"broken/BrokenMod", TestMods.modClass("broken/BrokenMod", "broken", null, true)
|
||||||
|
));
|
||||||
|
|
||||||
|
Forge forge = this.forge();
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile));
|
||||||
|
|
||||||
|
assertEquals(List.of("'broken': onLoad() threw java.lang.IllegalStateException: broken."), e.problems());
|
||||||
|
assertEquals(Lifecycle.Phase.BOOTING, forge.phase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void errorsOfModsInStartedAndStoppingReachNeitherTheGameNorTheOtherMods() throws Exception
|
||||||
|
{
|
||||||
|
TestMods.folder(this.mods, "economy", TestMods.toml("economy", "economy.EconomyMod", ForgeTest.USES_GAME), Map.of(
|
||||||
|
"economy/EconomyMod", TestMods.modClass("economy/EconomyMod", "economy", null, false)
|
||||||
|
));
|
||||||
|
TestMods.folder(this.mods, "errors", TestMods.toml("errors", ErrorMod.class.getName(), "[dependencies]\neconomy = \"1.0\"\n"), Map.of(
|
||||||
|
"testmods/ErrorMod", TestMods.classFile(ErrorMod.class)
|
||||||
|
));
|
||||||
|
|
||||||
|
Forge forge = this.load();
|
||||||
|
|
||||||
|
forge.started();
|
||||||
|
forge.stopping();
|
||||||
|
|
||||||
|
assertEquals(List.of("economy:new", "economy:onLoad", "economy:onServerStarted", "economy:onStopping"), Recorder.EVENTS, "economy is stopped after errors stopped");
|
||||||
|
assertEquals(Lifecycle.Phase.STOPPING, forge.phase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void failsWhenTheEntryPointIsNoMod() throws IOException
|
||||||
|
{
|
||||||
|
TestMods.folder(this.mods, "plain", TestMods.toml("plain", "plain.Accounts", ForgeTest.USES_GAME), Map.of(
|
||||||
|
"plain/Accounts", TestMods.pingClass("plain/Accounts")
|
||||||
|
));
|
||||||
|
TestMods.folder(this.mods, "missing", TestMods.toml("missing", "missing.Gone", ""), Map.of());
|
||||||
|
|
||||||
|
ModLoadException missing = assertThrows(ModLoadException.class, this::load);
|
||||||
|
assertEquals(List.of("'missing': entry point 'missing.Gone' cannot be loaded: java.lang.ClassNotFoundException: missing.Gone (not visible to mod 'missing')."), missing.problems());
|
||||||
|
|
||||||
|
try (Stream<Path> paths = Files.walk(this.mods.resolve("missing"))) { paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete()); }
|
||||||
|
|
||||||
|
ModLoadException plain = assertThrows(ModLoadException.class, this::load);
|
||||||
|
assertEquals(List.of("'plain': entry point 'plain.Accounts' does not extend 'dev.overlord.zomboidforge.api.Mod'."), plain.problems());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void settingsOfOptionalValues() throws Exception
|
||||||
|
{
|
||||||
|
this.contextMod("", "greeting = \"a\"\nlimit = 1\nextra = \"b\"\n[prices]\n");
|
||||||
|
|
||||||
|
Object mod = this.load().mods().getFirst().mod();
|
||||||
|
Object settings = ForgeTest.field(mod, "settings");
|
||||||
|
|
||||||
|
assertEquals(Optional.of("b"), settings.getClass().getMethod("extra").invoke(settings));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object field(Object mod, String name) throws ReflectiveOperationException { return mod.getClass().getField(name).get(mod); }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modsUseTheirThreadTheMainThreadAndEvents() throws Exception
|
||||||
|
{
|
||||||
|
TestMods.folder(this.mods, "threads", TestMods.toml("threads", ThreadMod.class.getName(), ""), Map.of(
|
||||||
|
"testmods/ThreadMod", TestMods.classFile(ThreadMod.class),
|
||||||
|
"testmods/ThreadMod$Greeting", TestMods.classFile(ThreadMod.Greeting.class)
|
||||||
|
));
|
||||||
|
|
||||||
|
Forge forge = this.load();
|
||||||
|
Object mod = forge.mods().getFirst().mod();
|
||||||
|
String main = Thread.currentThread().getName();
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<String> log = (List<String>) ForgeTest.field(mod, "log");
|
||||||
|
|
||||||
|
forge.started();
|
||||||
|
ForgeTest.await(() -> log.contains("work on zf-mod-threads"));
|
||||||
|
assertEquals(List.of("work on zf-mod-threads"), log, "the hand-off to main waits for the tick");
|
||||||
|
|
||||||
|
forge.tick();
|
||||||
|
assertEquals(1L, ForgeTest.field(mod, "ticks"));
|
||||||
|
assertEquals("result on " + main, log.getLast());
|
||||||
|
|
||||||
|
// The listener is registered for the Greeting class of the mod's own class loader.
|
||||||
|
Class<?> greeting = mod.getClass().getClassLoader().loadClass(ThreadMod.Greeting.class.getName());
|
||||||
|
forge.post((Event) greeting.getConstructor(String.class).newInstance("hi"));
|
||||||
|
ForgeTest.await(() -> log.contains("greeting hi on zf-mod-threads"));
|
||||||
|
|
||||||
|
forge.stopping();
|
||||||
|
assertEquals("stopping", log.getLast());
|
||||||
|
assertEquals(Lifecycle.Phase.STOPPING, forge.phase());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void await(BooleanSupplier condition) throws InterruptedException
|
||||||
|
{
|
||||||
|
long deadline = System.nanoTime() + 5_000_000_000L;
|
||||||
|
|
||||||
|
while (!condition.getAsBoolean())
|
||||||
|
{
|
||||||
|
if (System.nanoTime() > deadline) throw new AssertionError("Condition not met within 5 s.");
|
||||||
|
Thread.sleep(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package dev.overlord.zomboidforge.core;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
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 LifecycleTest
|
||||||
|
{
|
||||||
|
@Test
|
||||||
|
void advancesInOrder()
|
||||||
|
{
|
||||||
|
Lifecycle lifecycle = new Lifecycle();
|
||||||
|
assertEquals(Lifecycle.Phase.BOOTING, lifecycle.phase());
|
||||||
|
|
||||||
|
lifecycle.loaded();
|
||||||
|
assertEquals(Lifecycle.Phase.LOADED, lifecycle.phase());
|
||||||
|
|
||||||
|
lifecycle.started();
|
||||||
|
assertEquals(Lifecycle.Phase.RUNNING, lifecycle.phase());
|
||||||
|
|
||||||
|
assertTrue(lifecycle.stopping());
|
||||||
|
assertEquals(Lifecycle.Phase.STOPPING, lifecycle.phase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsSkippedOrRepeatedPhases()
|
||||||
|
{
|
||||||
|
Lifecycle lifecycle = new Lifecycle();
|
||||||
|
|
||||||
|
IllegalStateException e = assertThrows(IllegalStateException.class, lifecycle::started);
|
||||||
|
assertEquals("Cannot enter phase 'RUNNING' from 'BOOTING', only from 'LOADED'.", e.getMessage());
|
||||||
|
assertEquals(Lifecycle.Phase.BOOTING, lifecycle.phase());
|
||||||
|
|
||||||
|
lifecycle.loaded();
|
||||||
|
assertThrows(IllegalStateException.class, lifecycle::loaded);
|
||||||
|
assertEquals(Lifecycle.Phase.LOADED, lifecycle.phase());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void stopsFromAnyPhaseOnce()
|
||||||
|
{
|
||||||
|
Lifecycle booting = new Lifecycle();
|
||||||
|
assertTrue(booting.stopping());
|
||||||
|
assertFalse(booting.stopping());
|
||||||
|
|
||||||
|
Lifecycle loaded = new Lifecycle();
|
||||||
|
loaded.loaded();
|
||||||
|
assertTrue(loaded.stopping());
|
||||||
|
assertThrows(IllegalStateException.class, loaded::started);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package dev.overlord.zomboidforge.core;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.ResourceBundle;
|
||||||
|
|
||||||
|
/** {@link System.Logger} that keeps every message as {@code "LEVEL: message"}, with {@code " (<exception>)"} when one is given. */
|
||||||
|
public final class RecordingLogger implements System.Logger
|
||||||
|
{
|
||||||
|
public final List<String> messages = Collections.synchronizedList(new ArrayList<>());
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getName() { return "test"; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isLoggable(Level level) { return true; }
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String message, @Nullable Throwable thrown)
|
||||||
|
{
|
||||||
|
this.messages.add(level.getName() + ": " + message + (thrown == null ? "" : " (" + thrown + ")"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void log(Level level, @Nullable ResourceBundle bundle, @Nullable String format, @Nullable Object @Nullable ... parameters)
|
||||||
|
{
|
||||||
|
this.log(level, bundle, format == null || parameters == null ? format : MessageFormat.format(format, parameters), (Throwable) null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.config;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.time.Duration;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class ForgeSettingsTest
|
||||||
|
{
|
||||||
|
@TempDir
|
||||||
|
Path directory;
|
||||||
|
|
||||||
|
private ForgeSettings read(String toml) throws Exception
|
||||||
|
{
|
||||||
|
Path file = this.directory.resolve(ForgeSettings.FILE);
|
||||||
|
Files.writeString(file, toml);
|
||||||
|
|
||||||
|
return ForgeSettings.read(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void defaultsWithoutFileOrKeys() throws Exception
|
||||||
|
{
|
||||||
|
assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)));
|
||||||
|
assertEquals(ForgeSettings.DEFAULTS, this.read("[main_thread]\n"));
|
||||||
|
assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)), ForgeSettings.DEFAULTS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void readsEveryKey() throws Exception
|
||||||
|
{
|
||||||
|
assertEquals(
|
||||||
|
new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0)),
|
||||||
|
this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsUnknownKeysAndInvalidValues()
|
||||||
|
{
|
||||||
|
IllegalArgumentException unknown = assertThrows(IllegalArgumentException.class, () -> this.read("[main_thread]\nbudget = 5\n[other]\n"));
|
||||||
|
assertEquals("Unknown key 'main_thread.budget'. Unknown key 'other'.", unknown.getMessage());
|
||||||
|
|
||||||
|
IllegalArgumentException range = assertThrows(IllegalArgumentException.class, () -> this.read("[main_thread]\nbudget_ms = 0\n[shutdown]\ntimeout_s = -1\n"));
|
||||||
|
assertEquals("'main_thread.budget_ms' must be at least 1, found 0. 'shutdown.timeout_s' must not be negative, found -1.", range.getMessage());
|
||||||
|
|
||||||
|
IllegalArgumentException type = assertThrows(IllegalArgumentException.class, () -> this.read("[shutdown]\ntimeout_s = \"10\"\n"));
|
||||||
|
assertEquals("'shutdown.timeout_s' must be an integer, found \"10\".", type.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.config;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.core.ConsoleLogger;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class TomlModConfigTest
|
||||||
|
{
|
||||||
|
private enum Mode { EASY, HARD }
|
||||||
|
|
||||||
|
private record Limits(int perDay, double factor) {}
|
||||||
|
|
||||||
|
private record Settings(
|
||||||
|
String greeting,
|
||||||
|
boolean enabled,
|
||||||
|
long maxBalance,
|
||||||
|
float ratio,
|
||||||
|
Mode mode,
|
||||||
|
List<String> admins,
|
||||||
|
Map<String, Long> prices,
|
||||||
|
Limits limits,
|
||||||
|
Optional<String> motd,
|
||||||
|
Optional<Integer> httpPort
|
||||||
|
) {}
|
||||||
|
|
||||||
|
private static TomlModConfig config(String defaults, String settings)
|
||||||
|
{
|
||||||
|
return new TomlModConfig(TomlTree.merge(TomlTree.parse(defaults), TomlTree.parse(settings)), new ConsoleLogger("test"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void bindsEverySupportedTypeOverDefaults()
|
||||||
|
{
|
||||||
|
TomlModConfig config = TomlModConfigTest.config("""
|
||||||
|
greeting = "default"
|
||||||
|
enabled = true
|
||||||
|
max_balance = 100
|
||||||
|
ratio = 0.5
|
||||||
|
mode = "easy"
|
||||||
|
admins = ["a"]
|
||||||
|
|
||||||
|
[prices]
|
||||||
|
apple = 3
|
||||||
|
|
||||||
|
[limits]
|
||||||
|
per_day = 10
|
||||||
|
factor = 1.5
|
||||||
|
""", """
|
||||||
|
greeting = "hi"
|
||||||
|
mode = "HARD"
|
||||||
|
http_port = 8080
|
||||||
|
unused = 1
|
||||||
|
|
||||||
|
[limits]
|
||||||
|
per_day = 20
|
||||||
|
""");
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
new Settings("hi", true, 100, 0.5F, Mode.HARD, List.of("a"), Map.of("apple", 3L), new Limits(20, 1.5), Optional.empty(), Optional.of(8080)),
|
||||||
|
config.bind(Settings.class)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsEveryProblem()
|
||||||
|
{
|
||||||
|
TomlModConfig config = TomlModConfigTest.config("", """
|
||||||
|
greeting = 1
|
||||||
|
enabled = "yes"
|
||||||
|
mode = "medium"
|
||||||
|
admins = ["a", 2]
|
||||||
|
prices = 5
|
||||||
|
http_port = 99999999999
|
||||||
|
|
||||||
|
[limits]
|
||||||
|
per_day = 1.5
|
||||||
|
""");
|
||||||
|
|
||||||
|
IllegalStateException e = assertThrows(IllegalStateException.class, () -> config.bind(Settings.class));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
"config.toml does not match 'Settings': "
|
||||||
|
+ "'greeting' must be a string, found 1. "
|
||||||
|
+ "'enabled' must be true or false, found \"yes\". "
|
||||||
|
+ "'max_balance' is missing. "
|
||||||
|
+ "'ratio' is missing. "
|
||||||
|
+ "'mode' must be one of \"easy\", \"hard\", found \"medium\". "
|
||||||
|
+ "'admins[1]' must be a string, found 2. "
|
||||||
|
+ "'prices' must be a table, found 5. "
|
||||||
|
+ "'limits.per_day' must be an integer, found 1.5. "
|
||||||
|
+ "'limits.factor' is missing. "
|
||||||
|
+ "'http_port' must be between -2147483648 and 2147483647, found 99999999999.",
|
||||||
|
e.getMessage()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void readsSingleValuesByPath()
|
||||||
|
{
|
||||||
|
TomlModConfig config = TomlModConfigTest.config("[limits]\nper_day = 10\n", "");
|
||||||
|
|
||||||
|
assertEquals(Optional.of(10L), config.get("limits.per_day", Long.class));
|
||||||
|
assertEquals(Optional.of(10), config.get("limits.per_day", Integer.class));
|
||||||
|
assertEquals(Optional.empty(), config.get("limits.other", Long.class));
|
||||||
|
assertEquals(Optional.empty(), config.get("missing.per_day", Long.class));
|
||||||
|
assertThrows(IllegalStateException.class, () -> config.get("limits.per_day", String.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void convertsComponentNamesToKeys()
|
||||||
|
{
|
||||||
|
assertEquals("max_balance", RecordBinder.key("maxBalance"));
|
||||||
|
assertEquals("http_port", RecordBinder.key("httpPort"));
|
||||||
|
assertEquals("http_port", RecordBinder.key("HTTPPort"));
|
||||||
|
assertEquals("api_key2", RecordBinder.key("apiKey2"));
|
||||||
|
assertEquals("name", RecordBinder.key("name"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mergesTablesKeyByKey()
|
||||||
|
{
|
||||||
|
Map<String, Object> merged = TomlTree.merge(
|
||||||
|
TomlTree.parse("a = 1\n[t]\nx = 1\ny = 2\n"),
|
||||||
|
TomlTree.parse("b = 2.5\n[t]\ny = 3\n")
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(Map.of("a", 1L, "b", 2.5, "t", Map.of("x", 1L, "y", 3L)), merged);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
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.net.URL;
|
||||||
|
import java.net.URLClassLoader;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class ModClassLoaderTest
|
||||||
|
{
|
||||||
|
@TempDir
|
||||||
|
Path directory;
|
||||||
|
|
||||||
|
private GameClasses game;
|
||||||
|
private URLClassLoader parent;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws IOException
|
||||||
|
{
|
||||||
|
Path gameJar = TestMods.gameJar(this.directory.resolve("projectzomboid.jar"));
|
||||||
|
|
||||||
|
this.game = GameClasses.open(gameJar);
|
||||||
|
this.parent = new URLClassLoader(new URL[]{gameJar.toUri().toURL()}, ModClassLoaderTest.class.getClassLoader());
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() throws IOException
|
||||||
|
{
|
||||||
|
this.game.close();
|
||||||
|
this.parent.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ModClassLoader loader(String id, Map<String, byte[]> own, Map<String, byte[]> library, List<ModClassLoader> dependencies, @Nullable GameClasses game) throws IOException
|
||||||
|
{
|
||||||
|
Path jar = this.directory.resolve(id + ".jar");
|
||||||
|
Path lib = this.directory.resolve(id + "-lib.jar");
|
||||||
|
|
||||||
|
TestMods.jar(jar, null, own);
|
||||||
|
TestMods.jar(lib, null, library);
|
||||||
|
|
||||||
|
return new ModClassLoader(id, jar, List.of(lib), this.parent, dependencies, game);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void seesTheJdkAndTheApiButNotZomboidForgeInternals() throws Exception
|
||||||
|
{
|
||||||
|
try (ModClassLoader loader = this.loader("plain", Map.of(), Map.of(), List.of(), null))
|
||||||
|
{
|
||||||
|
assertSame(String.class, loader.loadClass("java.lang.String"));
|
||||||
|
assertSame(java.sql.Connection.class, loader.loadClass("java.sql.Connection"));
|
||||||
|
assertSame(dev.overlord.zomboidforge.api.Mod.class, loader.loadClass("dev.overlord.zomboidforge.api.Mod"));
|
||||||
|
|
||||||
|
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("dev.overlord.zomboidforge.api.internal.ModBinding"));
|
||||||
|
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("dev.overlord.zomboidforge.core.Forge"));
|
||||||
|
assertThrows(ClassNotFoundException.class, () -> loader.loadClass("org.junit.jupiter.api.Test"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void seesGameClassesOnlyWithDeclaredGameVersions() throws Exception
|
||||||
|
{
|
||||||
|
try (ModClassLoader without = this.loader("without", Map.of(), Map.of(), List.of(), null);
|
||||||
|
ModClassLoader with = this.loader("with", Map.of(), Map.of(), List.of(), this.game))
|
||||||
|
{
|
||||||
|
ClassNotFoundException e = assertThrows(ClassNotFoundException.class, () -> without.loadClass("zombie.core.Core"));
|
||||||
|
assertEquals("zombie.core.Core (not visible to mod 'without')", e.getMessage());
|
||||||
|
|
||||||
|
assertSame(this.parent.loadClass("zombie.core.Core"), with.loadClass("zombie.core.Core"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ownLibrariesTakePrecedenceOverGameLibraries() throws Exception
|
||||||
|
{
|
||||||
|
Map<String, byte[]> shared = Map.of("com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null));
|
||||||
|
|
||||||
|
try (ModClassLoader loader = this.loader("bundled", Map.of(), shared, List.of(), this.game))
|
||||||
|
{
|
||||||
|
assertSame(loader, loader.loadClass("com.example.Shared").getClassLoader());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void dependenciesShareTheirOwnJarButNotTheirLibraries() throws Exception
|
||||||
|
{
|
||||||
|
try (ModClassLoader economy = this.loader("economy", Map.of("economy/Accounts", TestMods.pingClass("economy/Accounts")), Map.of("economy/lib/Util", TestMods.type("economy/lib/Util", "java/lang/Object", null)), List.of(), null);
|
||||||
|
ModClassLoader shop = this.loader("shop", Map.of(), Map.of(), List.of(economy), null))
|
||||||
|
{
|
||||||
|
assertSame(economy.loadClass("economy.Accounts"), shop.loadClass("economy.Accounts"));
|
||||||
|
assertThrows(ClassNotFoundException.class, () -> shop.loadClass("economy.lib.Util"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
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 ModDescriptorTest
|
||||||
|
{
|
||||||
|
@Test
|
||||||
|
void readsEveryKey() throws ModLoadException
|
||||||
|
{
|
||||||
|
ModDescriptor descriptor = ModDescriptor.parse("""
|
||||||
|
id = "shop"
|
||||||
|
name = "Shop"
|
||||||
|
version = "1.2.0"
|
||||||
|
entrypoint = "com.example.shop.ShopMod"
|
||||||
|
api = "0.3"
|
||||||
|
game = ["42.21", "42.22"]
|
||||||
|
previous_ids = ["store"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
economy = "2.1"
|
||||||
|
""");
|
||||||
|
|
||||||
|
assertEquals("shop", descriptor.id());
|
||||||
|
assertEquals("Shop", descriptor.name());
|
||||||
|
assertEquals(ModVersion.parse("1.2.0"), descriptor.version());
|
||||||
|
assertEquals("com.example.shop.ShopMod", descriptor.entrypoint());
|
||||||
|
assertEquals(ModVersion.parse("0.3"), descriptor.api());
|
||||||
|
assertEquals(List.of("42.21", "42.22"), descriptor.game());
|
||||||
|
assertEquals(List.of("store"), descriptor.previousIds());
|
||||||
|
assertEquals(Map.of("economy", ModVersion.parse("2.1")), descriptor.dependencies());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void optionalKeysDefault() throws ModLoadException
|
||||||
|
{
|
||||||
|
ModDescriptor descriptor = ModDescriptor.parse(TestMods.toml("hello", "a.Hello", ""));
|
||||||
|
|
||||||
|
assertEquals("hello", descriptor.name());
|
||||||
|
assertTrue(descriptor.game().isEmpty());
|
||||||
|
assertTrue(descriptor.previousIds().isEmpty());
|
||||||
|
assertTrue(descriptor.dependencies().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void collectsEveryProblem()
|
||||||
|
{
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDescriptor.parse("""
|
||||||
|
version = "one"
|
||||||
|
api = "0.3"
|
||||||
|
game = []
|
||||||
|
colour = "red"
|
||||||
|
"""));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of(
|
||||||
|
"Unknown key 'colour'.",
|
||||||
|
"'id' is missing.",
|
||||||
|
"'version' = 'one' is not a version such as '1.2.0'.",
|
||||||
|
"'entrypoint' is missing.",
|
||||||
|
"'game' is empty; leave it out when the mod uses no game classes."
|
||||||
|
),
|
||||||
|
e.problems()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validatesIds()
|
||||||
|
{
|
||||||
|
assertTrue(ModDescriptor.isValidId("shop"));
|
||||||
|
assertTrue(ModDescriptor.isValidId("shop_2"));
|
||||||
|
assertFalse(ModDescriptor.isValidId("shop__2"), "'__' separates id and table in storage");
|
||||||
|
assertFalse(ModDescriptor.isValidId("shop_"));
|
||||||
|
assertFalse(ModDescriptor.isValidId("Shop"));
|
||||||
|
assertFalse(ModDescriptor.isValidId("2shop"));
|
||||||
|
assertFalse(ModDescriptor.isValidId("core"));
|
||||||
|
assertFalse(ModDescriptor.isValidId("a".repeat(33)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsBadReferences()
|
||||||
|
{
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDescriptor.parse(TestMods.toml("shop", "a.Shop", """
|
||||||
|
game = ["42.x"]
|
||||||
|
previous_ids = ["shop"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
shop = "1.0"
|
||||||
|
""")));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of(
|
||||||
|
"'game' contains '42.x', which is not a version prefix such as '42' or '42.21'.",
|
||||||
|
"'previous_ids' contains 'shop', which is not a valid earlier mod id.",
|
||||||
|
"'dependencies' contains the mod itself."
|
||||||
|
),
|
||||||
|
e.problems()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsInvalidToml()
|
||||||
|
{
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDescriptor.parse("id = "));
|
||||||
|
|
||||||
|
assertTrue(e.problems().getFirst().startsWith("Not valid TOML: "), e.problems().getFirst());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.core.ConsoleLogger;
|
||||||
|
|
||||||
|
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.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class ModDiscoveryTest
|
||||||
|
{
|
||||||
|
private static final System.Logger LOGGER = new ConsoleLogger("test");
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path mods;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void readsEveryFolderSortedByName() throws Exception
|
||||||
|
{
|
||||||
|
TestMods.folder(this.mods, "shop", TestMods.toml("shop", "a.Shop", ""), Map.of());
|
||||||
|
Path economy = TestMods.folder(this.mods, "economy", TestMods.toml("economy", "a.Economy", ""), Map.of());
|
||||||
|
|
||||||
|
Path libraries = Files.createDirectories(economy.resolve("lib"));
|
||||||
|
TestMods.jar(libraries.resolve("b.jar"), null, Map.of());
|
||||||
|
TestMods.jar(libraries.resolve("a.jar"), null, Map.of());
|
||||||
|
Files.writeString(libraries.resolve("notes.txt"), "not a jar");
|
||||||
|
Files.writeString(economy.resolve("config.toml"), "");
|
||||||
|
Files.writeString(this.mods.resolve(".hidden"), "");
|
||||||
|
|
||||||
|
List<ModDiscovery.Candidate> candidates = ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER);
|
||||||
|
|
||||||
|
assertEquals(List.of("economy", "shop"), candidates.stream().map(ModDiscovery.Candidate::id).toList());
|
||||||
|
assertEquals(economy.resolve("economy.jar"), candidates.getFirst().jar());
|
||||||
|
assertEquals(List.of(libraries.resolve("a.jar"), libraries.resolve("b.jar")), candidates.getFirst().libraries());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsTheProblemsOfEveryFolder() throws IOException
|
||||||
|
{
|
||||||
|
Files.writeString(this.mods.resolve("loose.jar"), "");
|
||||||
|
|
||||||
|
Files.createDirectories(this.mods.resolve("empty"));
|
||||||
|
|
||||||
|
Path extra = TestMods.folder(this.mods, "extra", TestMods.toml("extra", "a.Extra", ""), Map.of());
|
||||||
|
TestMods.jar(extra.resolve("extra-1.0.jar"), null, Map.of());
|
||||||
|
|
||||||
|
TestMods.folder(this.mods, "renamed", TestMods.toml("other", "a.Other", ""), Map.of());
|
||||||
|
TestMods.folder(this.mods, "plain", null, Map.of());
|
||||||
|
TestMods.folder(this.mods, "typo", TestMods.toml("typo", "a.Typo", "colour = \"red\"\n"), Map.of());
|
||||||
|
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of(
|
||||||
|
"'empty': 'empty.jar' is missing.",
|
||||||
|
"'extra': 'extra-1.0.jar' is not 'extra.jar'; the folder may contain only the mod's own jar (libraries go into 'lib/').",
|
||||||
|
"'loose.jar': not a folder; every mod is a folder 'mods/<id>/' with '<id>.jar' inside.",
|
||||||
|
"'plain': 'plain.jar' contains no 'META-INF/zomboidforge/mod.toml'.",
|
||||||
|
"'renamed': The folder is named 'renamed', but 'mod.toml' declares the id 'other'.",
|
||||||
|
"'typo': mod.toml: Unknown key 'colour'."
|
||||||
|
),
|
||||||
|
e.problems()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void readsTheForgeTableAndReportsBadSettings() throws Exception
|
||||||
|
{
|
||||||
|
Path off = TestMods.folder(this.mods, "off", TestMods.toml("off", "a.Off", ""), Map.of());
|
||||||
|
Files.writeString(off.resolve("config.toml"), "[forge]\nenabled = false\n");
|
||||||
|
|
||||||
|
Path typo = TestMods.folder(this.mods, "typo", TestMods.toml("typo", "a.Typo", ""), Map.of());
|
||||||
|
Files.writeString(typo.resolve("config.toml"), "[forge]\nenable = false\nenabled = \"no\"\n");
|
||||||
|
|
||||||
|
Path broken = TestMods.folder(this.mods, "broken", TestMods.toml("broken", "a.Broken", ""), Map.of());
|
||||||
|
Files.writeString(broken.resolve("config.toml"), "limit = \n");
|
||||||
|
|
||||||
|
TestMods.folder(this.mods, "author", TestMods.toml("author", "a.Author", ""), "[forge\n", Map.of());
|
||||||
|
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER));
|
||||||
|
|
||||||
|
assertEquals(List.of("author", "broken", "typo", "typo"), e.problems().stream().map(problem -> problem.substring(1, problem.indexOf("'", 1))).toList());
|
||||||
|
assertEquals("'typo': 'config.toml': unknown key 'forge.enable'; [forge] only has 'enabled'.", e.problems().get(2));
|
||||||
|
assertEquals("'typo': 'config.toml': 'forge.enabled' must be true or false.", e.problems().get(3));
|
||||||
|
|
||||||
|
Files.delete(typo.resolve("config.toml"));
|
||||||
|
Files.writeString(broken.resolve("config.toml"), "");
|
||||||
|
TestMods.folder(this.mods, "author", TestMods.toml("author", "a.Author", ""), "[forge]\nenabled = false\n", Map.of());
|
||||||
|
|
||||||
|
List<ModDiscovery.Candidate> candidates = ModDiscovery.discover(this.mods, ModDiscoveryTest.LOGGER);
|
||||||
|
assertEquals(List.of("author", "broken", "off", "typo"), candidates.stream().map(ModDiscovery.Candidate::id).toList());
|
||||||
|
assertEquals(List.of(false, true, false, true), candidates.stream().map(ModDiscovery.Candidate::enabled).toList());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class ModResolverTest
|
||||||
|
{
|
||||||
|
private static final GameVersion GAME = GameVersion.parse("42.21.0");
|
||||||
|
private static final ModVersion API = ModVersion.parse("0.3.1");
|
||||||
|
|
||||||
|
private static ModDiscovery.Candidate mod(String id, String extra) throws ModLoadException
|
||||||
|
{
|
||||||
|
Path directory = Path.of("mods", id);
|
||||||
|
return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)), true, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A mod built against API 0.4. */
|
||||||
|
private static ModDiscovery.Candidate newerApi(String id) throws ModLoadException
|
||||||
|
{
|
||||||
|
Path directory = Path.of("mods", id);
|
||||||
|
String toml = TestMods.toml(id, "a.Mod", "").replace("api = \"0.3\"", "api = \"0.4\"");
|
||||||
|
|
||||||
|
return new ModDiscovery.Candidate(directory, directory.resolve(id + ".jar"), List.of(), ModDescriptor.parse(toml), true, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> order(ModDiscovery.Candidate... candidates) throws ModLoadException
|
||||||
|
{
|
||||||
|
return ModResolver.resolve(Arrays.asList(candidates), ModResolverTest.GAME, ModResolverTest.API).stream().map(ModDiscovery.Candidate::id).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ordersDependenciesFirstOtherwiseById() throws ModLoadException
|
||||||
|
{
|
||||||
|
List<String> order = ModResolverTest.order(
|
||||||
|
ModResolverTest.mod("shop", "[dependencies]\neconomy = \"1.0\"\nbank = \"1.0\"\n"),
|
||||||
|
ModResolverTest.mod("bank", "[dependencies]\neconomy = \"1.0\"\n"),
|
||||||
|
ModResolverTest.mod("economy", ""),
|
||||||
|
ModResolverTest.mod("admin", "")
|
||||||
|
);
|
||||||
|
|
||||||
|
assertEquals(List.of("admin", "economy", "bank", "shop"), order);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsMissingAndOldDependencies() throws ModLoadException
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate shop = ModResolverTest.mod("shop", "[dependencies]\neconomy = \"2.0\"\nbank = \"1.0\"\n");
|
||||||
|
ModDiscovery.Candidate economy = ModResolverTest.mod("economy", "");
|
||||||
|
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModResolverTest.order(shop, economy));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of(
|
||||||
|
"'shop': requires 'bank' 1.0.0 or newer, which is not installed.",
|
||||||
|
"'shop': requires 'economy' 2.0.0 or newer, 1.0.0 is installed."
|
||||||
|
),
|
||||||
|
e.problems()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsCycles() throws ModLoadException
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate a = ModResolverTest.mod("a", "[dependencies]\nb = \"1.0\"\n");
|
||||||
|
ModDiscovery.Candidate b = ModResolverTest.mod("b", "[dependencies]\nc = \"1.0\"\n");
|
||||||
|
ModDiscovery.Candidate c = ModResolverTest.mod("c", "[dependencies]\na = \"1.0\"\n");
|
||||||
|
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModResolverTest.order(a, b, c));
|
||||||
|
|
||||||
|
assertEquals(List.of("'a': dependency cycle 'a' -> 'b' -> 'c' -> 'a'."), e.problems());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checksGameAndApiVersions() throws ModLoadException
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate matching = ModResolverTest.mod("matching", "game = [\"42.20\", \"42.21\"]\n");
|
||||||
|
ModDiscovery.Candidate old = ModResolverTest.mod("old", "game = [\"41\"]\n");
|
||||||
|
ModDiscovery.Candidate newer = ModResolverTest.newerApi("newer");
|
||||||
|
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModResolverTest.order(matching, old, newer));
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of(
|
||||||
|
"'newer': built against ZomboidForge API 0.4.0, the server provides 0.3.1.",
|
||||||
|
"'old': supports Project Zomboid [41], the server runs 42.21.0."
|
||||||
|
),
|
||||||
|
e.problems()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void skipsTheApiCheckWithoutAnApiVersion() throws ModLoadException
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate newer = ModResolverTest.newerApi("newer");
|
||||||
|
|
||||||
|
assertEquals(List.of(newer), ModResolver.resolve(List.of(newer), ModResolverTest.GAME, null));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import dev.overlord.zomboidforge.api.GameVersion;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
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.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
class ModVerifierTest
|
||||||
|
{
|
||||||
|
private static final GameVersion GAME = GameVersion.parse("42.21.0");
|
||||||
|
private static final String CORE = "zombie/core/Core";
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path directory;
|
||||||
|
|
||||||
|
private GameClasses game;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws IOException { this.game = GameClasses.open(TestMods.gameJar(this.directory.resolve("projectzomboid.jar"))); }
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() throws IOException { this.game.close(); }
|
||||||
|
|
||||||
|
private ModDiscovery.Candidate mod(String id, String extra, Map<String, byte[]> classes, Map<String, byte[]> library) throws Exception
|
||||||
|
{
|
||||||
|
Path folder = TestMods.folder(this.directory.resolve("mods"), id, TestMods.toml(id, "a.Mod", extra), classes);
|
||||||
|
List<Path> libraries = List.of();
|
||||||
|
|
||||||
|
if (!library.isEmpty()) {
|
||||||
|
Path jar = Files.createDirectories(folder.resolve("lib")).resolve("library.jar");
|
||||||
|
TestMods.jar(jar, null, library);
|
||||||
|
libraries = List.of(jar);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ModDiscovery.Candidate(folder, folder.resolve(id + ".jar"), libraries, ModDescriptor.parse(TestMods.toml(id, "a.Mod", extra)), true, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> problems(ModDiscovery.Candidate... candidates)
|
||||||
|
{
|
||||||
|
ModLoadException e = assertThrows(ModLoadException.class, () -> ModVerifier.verify(List.of(candidates), this.game, ModVerifierTest.GAME));
|
||||||
|
return e.problems();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void acceptsGameUseWithDeclaredVersionsThatLinks() throws Exception
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate mod = this.mod("linked", "game = [\"42\"]\n", Map.of("a/Use", TestMods.user("a/Use",
|
||||||
|
TestMods.Use.staticCall(ModVerifierTest.CORE, "version", "()I"),
|
||||||
|
TestMods.Use.virtualCall(ModVerifierTest.CORE, "inherited", "()V"),
|
||||||
|
TestMods.Use.virtualCall(ModVerifierTest.CORE, "toString", "()Ljava/lang/String;"),
|
||||||
|
TestMods.Use.field(ModVerifierTest.CORE, "counter", "I"),
|
||||||
|
TestMods.Use.type("java/util/List")
|
||||||
|
)), Map.of());
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsMissingGameClassesAndMembers() throws Exception
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate mod = this.mod("linked", "game = [\"42\"]\n", Map.of("a/Use", TestMods.user("a/Use",
|
||||||
|
TestMods.Use.staticCall(ModVerifierTest.CORE, "gone", "()V"),
|
||||||
|
TestMods.Use.field(ModVerifierTest.CORE, "missing", "I"),
|
||||||
|
TestMods.Use.type("zombie/core/Removed")
|
||||||
|
)), Map.of());
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of("'linked': uses 'zombie.core.Removed', 'zombie.core.Core.gone()V', 'zombie.core.Core.missing:I', which do not exist in Project Zomboid 42.21.0."),
|
||||||
|
this.problems(mod)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void requiresGameVersionsForGameClassesIncludingBundledLibraries() throws Exception
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate mod = this.mod("plain", "", Map.of("a/Use", TestMods.user("a/Use",
|
||||||
|
TestMods.Use.staticCall(ModVerifierTest.CORE, "version", "()I"),
|
||||||
|
TestMods.Use.type("com/example/Shared")
|
||||||
|
)), Map.of());
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of("'plain': uses classes of the Project Zomboid jar ('com.example.Shared', 'zombie.core.Core') but declares no 'game' versions in mod.toml."),
|
||||||
|
this.problems(mod)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ownLibrariesAndAnnotationsDoNotCountAsGameUse() throws Exception
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate mod = this.mod("bundled", "", Map.of(
|
||||||
|
"a/Use", TestMods.user("a/Use", TestMods.Use.type("com/example/Shared")),
|
||||||
|
"a/Annotated", TestMods.type("a/Annotated", "java/lang/Object", "Lorg/jetbrains/annotations/Nullable;")
|
||||||
|
), Map.of(
|
||||||
|
"com/example/Shared", TestMods.type("com/example/Shared", "java/lang/Object", null)
|
||||||
|
));
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> ModVerifier.verify(List.of(mod), this.game, ModVerifierTest.GAME));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reportsInternalClassesAndForbiddenPackages() throws Exception
|
||||||
|
{
|
||||||
|
ModDiscovery.Candidate mod = this.mod("sneaky", "game = [\"42\"]\n", Map.of(
|
||||||
|
"a/Use", TestMods.user("a/Use",
|
||||||
|
TestMods.Use.type("dev/overlord/zomboidforge/core/Forge"),
|
||||||
|
TestMods.Use.type("dev/overlord/zomboidforge/api/internal/ModBinding"),
|
||||||
|
TestMods.Use.type("dev/overlord/zomboidforge/api/Mod")
|
||||||
|
),
|
||||||
|
ModVerifierTest.CORE, TestMods.type(ModVerifierTest.CORE, "java/lang/Object", null),
|
||||||
|
"dev/overlord/zomboidforge/api/Fake", TestMods.type("dev/overlord/zomboidforge/api/Fake", "java/lang/Object", null)
|
||||||
|
), Map.of());
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
List.of(
|
||||||
|
"'sneaky': contains 'dev.overlord.zomboidforge.api.Fake', which is in a ZomboidForge package.",
|
||||||
|
"'sneaky': contains 'zombie.core.Core', which is a class of Project Zomboid.",
|
||||||
|
"'sneaky': uses 'dev.overlord.zomboidforge.api.internal.ModBinding', which is internal to ZomboidForge.",
|
||||||
|
"'sneaky': uses 'dev.overlord.zomboidforge.core.Forge', which is internal to ZomboidForge."
|
||||||
|
),
|
||||||
|
this.problems(mod)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void dependenciesProvideTheirOwnClasses() throws Exception
|
||||||
|
{
|
||||||
|
// Accounts.ping() calls Recorder, which is in the fake game jar.
|
||||||
|
ModDiscovery.Candidate economy = this.mod("economy", "game = [\"42\"]\n", Map.of("economy/Accounts", TestMods.pingClass("economy/Accounts")), Map.of());
|
||||||
|
ModDiscovery.Candidate shop = this.mod("shop", "[dependencies]\neconomy = \"1.0\"\n", Map.of("a/Use", TestMods.user("a/Use",
|
||||||
|
TestMods.Use.staticCall("economy/Accounts", "ping", "()V")
|
||||||
|
)), Map.of());
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> ModVerifier.verify(List.of(economy, shop), this.game, ModVerifierTest.GAME));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package dev.overlord.zomboidforge.core.mods;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
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 ModVersionTest
|
||||||
|
{
|
||||||
|
@Test
|
||||||
|
void parsesMissingPartsAsZero()
|
||||||
|
{
|
||||||
|
assertEquals(new ModVersion(1, 0, 0, null), ModVersion.parse("1"));
|
||||||
|
assertEquals(new ModVersion(1, 2, 0, null), ModVersion.parse("1.2"));
|
||||||
|
assertEquals(new ModVersion(1, 2, 3, "beta.1"), ModVersion.parse("1.2.3-beta.1"));
|
||||||
|
assertEquals("1.2.0", ModVersion.parse("1.2").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsOtherText()
|
||||||
|
{
|
||||||
|
assertTrue(ModVersion.tryParse("dev").isEmpty());
|
||||||
|
assertTrue(ModVersion.tryParse("1.2.3.4").isEmpty());
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> ModVersion.parse("v1.0"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsNumbersOutsideTheIntRange()
|
||||||
|
{
|
||||||
|
assertEquals(new ModVersion(999999999, 0, 0, null), ModVersion.parse("999999999"));
|
||||||
|
assertTrue(ModVersion.tryParse("99999999999").isEmpty());
|
||||||
|
assertTrue(ModVersion.tryParse("1.99999999999").isEmpty());
|
||||||
|
assertTrue(ModVersion.tryParse("1.0.99999999999").isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void preReleaseSortsBeforeRelease()
|
||||||
|
{
|
||||||
|
assertTrue(ModVersion.parse("1.0.0-rc.1").compareTo(ModVersion.parse("1.0.0")) < 0);
|
||||||
|
assertTrue(ModVersion.parse("1.0.0").compareTo(ModVersion.parse("1.0.1-rc.1")) < 0);
|
||||||
|
assertTrue(ModVersion.parse("1.10").compareTo(ModVersion.parse("1.9")) > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void apiCompatibility()
|
||||||
|
{
|
||||||
|
ModVersion api = ModVersion.parse("1.4.2");
|
||||||
|
|
||||||
|
assertTrue(api.providesApi(ModVersion.parse("1.0")));
|
||||||
|
assertTrue(api.providesApi(ModVersion.parse("1.4.2")));
|
||||||
|
assertFalse(api.providesApi(ModVersion.parse("1.5")));
|
||||||
|
assertFalse(api.providesApi(ModVersion.parse("2.0")));
|
||||||
|
assertFalse(ModVersion.parse("2.0").providesApi(ModVersion.parse("1.0")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void apiBeforeOneNeedsTheSameMinorVersion()
|
||||||
|
{
|
||||||
|
ModVersion api = ModVersion.parse("0.3.2");
|
||||||
|
|
||||||
|
assertTrue(api.providesApi(ModVersion.parse("0.3")));
|
||||||
|
assertFalse(api.providesApi(ModVersion.parse("0.2")));
|
||||||
|
assertFalse(api.providesApi(ModVersion.parse("0.4")));
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user