diff --git a/compose.yaml b/compose.yaml index f87453b..9c52511 100644 --- a/compose.yaml +++ b/compose.yaml @@ -6,22 +6,23 @@ services: image: localhost/zomboidforge:dev platform: linux/amd64 environment: - SERVER_NAME: ${SERVER_NAME:-zomboidforgetest} - SERVER_PASSWORD: ${SERVER_PASSWORD:-} - PUBLIC: ${PUBLIC:-} - PUBLIC_NAME: ${PUBLIC_NAME:-} - PORT: ${PORT:-16261} - UDP_PORT: ${UDP_PORT:-16262} - ADMIN_USERNAME: ${ADMIN_USERNAME:-} - ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} - SERVER_PRESET: ${SERVER_PRESET:-} - MODS: ${MODS:-} - WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-} - RCON_PASSWORD: ${RCON_PASSWORD:-} - UPNP: ${UPNP:-} - JVM_MIN_HEAP: ${JVM_MIN_HEAP:-} - JVM_MAX_HEAP: ${JVM_MAX_HEAP:-} - JVM_UNCOMMIT_DELAY: ${JVM_UNCOMMIT_DELAY:-} + SERVER_NAME: ${SERVER_NAME:-zomboidforgetest} + SERVER_PASSWORD: ${SERVER_PASSWORD:-} + PUBLIC: ${PUBLIC:-} + PUBLIC_NAME: ${PUBLIC_NAME:-} + PORT: ${PORT:-16261} + UDP_PORT: ${UDP_PORT:-16262} + ADMIN_USERNAME: ${ADMIN_USERNAME:-} + ADMIN_PASSWORD: ${ADMIN_PASSWORD:-} + SERVER_PRESET: ${SERVER_PRESET:-} + MODS: ${MODS:-} + WORKSHOP_ITEMS: ${WORKSHOP_ITEMS:-} + RCON_PASSWORD: ${RCON_PASSWORD:-} + UPNP: ${UPNP:-} + JVM_MIN_HEAP: ${JVM_MIN_HEAP:-} + JVM_MAX_HEAP: ${JVM_MAX_HEAP:-} + JVM_UNCOMMIT_DELAY: ${JVM_UNCOMMIT_DELAY:-} + ZF_EXPERIMENTAL_PERFORMANCE: ${ZF_EXPERIMENTAL_PERFORMANCE:-} ports: # Host and container ports must be equal: the server reports its own port # to Steam and to clients, so a remapped port is unreachable. diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index 839065d..a7f31a8 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -10,6 +10,7 @@ import dev.overlord.zomboidforge.api.storage.StorageException; import dev.overlord.zomboidforge.core.commands.ClientCommandSender; import dev.overlord.zomboidforge.core.commands.CommandRegistry; import dev.overlord.zomboidforge.core.commands.ModClientCommands; +import dev.overlord.zomboidforge.core.config.Feature; import dev.overlord.zomboidforge.core.config.ForgeSettings; import dev.overlord.zomboidforge.core.mods.GameClasses; import dev.overlord.zomboidforge.core.mods.ModDiscovery; @@ -100,6 +101,9 @@ public final class Forge public Lifecycle.Phase phase() { return this.lifecycle.phase(); } + /** The settings from {@code forge.toml} and the system properties; {@link ForgeSettings#DEFAULTS} until {@link #load} reads them. */ + public ForgeSettings settings() { return this.settings; } + public List mods() { return this.mods; } /** The admin command classes that mods registered, in registration order. */ @@ -119,8 +123,14 @@ public final class Forge { Path modsDirectory = this.directory.resolve(Forge.MODS); - try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE)); } - catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "': " + e.getMessage(), e); } + try { this.settings = ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), System.getProperties()); } + catch (IllegalArgumentException e) { throw new ModLoadException("'" + ForgeSettings.FILE + "' or system properties: " + e.getMessage(), e); } + + if (!this.settings.features().isEmpty()) + { + String features = this.settings.features().stream().sorted().map(Feature::key).collect(Collectors.joining(", ")); + this.logger.log(System.Logger.Level.INFO, "Features on: " + features + "."); + } this.queue.budget(this.settings.mainThreadBudget()); this.queue.bindToCurrentThread(); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/Feature.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/Feature.java new file mode 100644 index 0000000..5a198b0 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/Feature.java @@ -0,0 +1,44 @@ +package dev.overlord.zomboidforge.core.config; + +import java.util.Arrays; +import java.util.Locale; +import java.util.Optional; + +/** + * Optional behavior of ZomboidForge, off by default. Each feature has one key, from which its + * switches follow: + * + * + * + * Code that a feature switches reads it through {@link ForgeSettings#enabled(Feature)} of the + * running {@code Forge}, which has the defaults (every feature off) until the settings are read + * at load. + */ +public enum Feature +{ + /** + * Performance changes that alter timing or resource use: more threads, shorter waits. Off, + * the patched code does what vanilla does. + */ + EXPERIMENTAL_PERFORMANCE; + + /** Prefix of the system properties: {@code zomboidforge.features.}. */ + public static final String PROPERTY_PREFIX = "zomboidforge.features."; + + /** The key in {@code forge.toml} and in the property name: the lowercase constant name. */ + public String key() { return this.name().toLowerCase(Locale.ROOT); } + + /** The system property that switches this feature. */ + public String property() { return Feature.PROPERTY_PREFIX + this.key(); } + + /** The feature with {@code key}. */ + public static Optional byKey(String key) + { + return Arrays.stream(Feature.values()).filter(feature -> feature.key().equals(key)).findFirst(); + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/config/ForgeSettings.java b/core/src/main/java/dev/overlord/zomboidforge/core/config/ForgeSettings.java index 912b14f..80fbc80 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/config/ForgeSettings.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/config/ForgeSettings.java @@ -7,47 +7,58 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Properties; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; /** - * Global settings from {@code /forge.toml}. Every key is optional: - * - *
- * [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
- * 
+ * Global settings from {@code /forge.toml}. + * The system property {@code zomboidforge.features.} + * of a feature takes precedence over its key in the file. * * @param mainThreadBudget at least 1 ms * @param shutdownTimeout 0 or more + * @param features the features that are enabled */ -public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout) +public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout, Set features) { public static final String FILE = "forge.toml"; - public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)); + public static final ForgeSettings DEFAULTS = new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of()); - private record Document(Optional mainThread, Optional shutdown) {} + public ForgeSettings + { + features = Set.copyOf(features); + } + + /** Whether {@code feature} is on. */ + public boolean enabled(Feature feature) { return this.features.contains(feature); } + + private record Document(Optional mainThread, Optional shutdown, Optional> features) {} private record MainThread(Optional budgetMs) {} private record Shutdown(Optional timeoutS) {} /** - * The settings in {@code file}, or {@link #DEFAULTS} when it does not exist. + * The settings in {@code file}, the defaults for what it leaves out or when it does not + * exist; then the features switched in {@code properties} (the system properties). * * @throws IllegalArgumentException listing every problem: invalid TOML, unknown keys, values - * of the wrong type or out of range + * of the wrong type or out of range, feature properties that + * name no feature or are not {@code true} or {@code false} */ - public static ForgeSettings read(Path file) + public static ForgeSettings read(Path file, Properties properties) { - if (!Files.isRegularFile(file)) return ForgeSettings.DEFAULTS; + Map values = Map.of(); - Map values; - - try { values = TomlTree.parse(Files.readString(file)); } - catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); } + if (Files.isRegularFile(file)) + { + try { values = TomlTree.parse(Files.readString(file)); } + catch (IOException e) { throw new IllegalArgumentException("Cannot read '" + file + "': " + e.getMessage(), e); } + } RecordBinder binder = new RecordBinder(); @Nullable Document document = binder.record(values, Document.class, ""); @@ -63,8 +74,31 @@ public record ForgeSettings(Duration mainThreadBudget, Duration shutdownTimeout) if (budget < 1) problems.add("'main_thread.budget_ms' must be at least 1, found " + budget + "."); if (timeout < 0) problems.add("'shutdown.timeout_s' must not be negative, found " + timeout + "."); + Set features = EnumSet.noneOf(Feature.class); + + for (Map.Entry entry : new TreeMap<>(document.features().orElse(Map.of())).entrySet()) + { + Optional feature = Feature.byKey(entry.getKey()); + + if (feature.isEmpty()) problems.add("Unknown key 'features." + entry.getKey() + "'."); + else if (entry.getValue()) features.add(feature.get()); + } + + for (String name : new TreeSet<>(properties.stringPropertyNames())) + { + if (!name.startsWith(Feature.PROPERTY_PREFIX)) continue; + + Optional feature = Feature.byKey(name.substring(Feature.PROPERTY_PREFIX.length())); + String value = properties.getProperty(name); + + if (feature.isEmpty()) problems.add("Unknown system property '" + name + "'."); + else if (value.equalsIgnoreCase("true")) features.add(feature.get()); + else if (value.equalsIgnoreCase("false")) features.remove(feature.get()); + else problems.add("System property '" + name + "' must be true or false, found \"" + value + "\"."); + } + if (!problems.isEmpty()) throw new IllegalArgumentException(String.join(" ", problems)); - return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout)); + return new ForgeSettings(Duration.ofMillis(budget), Duration.ofSeconds(timeout), features); } } diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/config/FeatureTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/config/FeatureTest.java new file mode 100644 index 0000000..d4ab96d --- /dev/null +++ b/core/src/test/java/dev/overlord/zomboidforge/core/config/FeatureTest.java @@ -0,0 +1,25 @@ +package dev.overlord.zomboidforge.core.config; + +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class FeatureTest +{ + @Test + void keyAndPropertyFollowFromTheName() + { + assertEquals("experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.key()); + assertEquals("zomboidforge.features.experimental_performance", Feature.EXPERIMENTAL_PERFORMANCE.property()); + } + + @Test + void findsFeaturesByKey() + { + assertEquals(Optional.of(Feature.EXPERIMENTAL_PERFORMANCE), Feature.byKey("experimental_performance")); + assertEquals(Optional.empty(), Feature.byKey("EXPERIMENTAL_PERFORMANCE")); + assertEquals(Optional.empty(), Feature.byKey("faster")); + } +} diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/config/ForgeSettingsTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/config/ForgeSettingsTest.java index d141ff0..ebae76d 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/config/ForgeSettingsTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/config/ForgeSettingsTest.java @@ -6,9 +6,13 @@ import org.junit.jupiter.api.io.TempDir; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; +import java.util.Properties; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class ForgeSettingsTest { @@ -16,27 +20,41 @@ class ForgeSettingsTest Path directory; private ForgeSettings read(String toml) throws Exception + { + return this.read(toml, new Properties()); + } + + private ForgeSettings read(String toml, Properties properties) throws Exception { Path file = this.directory.resolve(ForgeSettings.FILE); Files.writeString(file, toml); - return ForgeSettings.read(file); + return ForgeSettings.read(file, properties); + } + + private static Properties properties(String... namesAndValues) + { + Properties properties = new Properties(); + for (int i = 0; i < namesAndValues.length; i += 2) properties.setProperty(namesAndValues[i], namesAndValues[i + 1]); + + return properties; } @Test void defaultsWithoutFileOrKeys() throws Exception { - assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE))); + assertEquals(ForgeSettings.DEFAULTS, ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), new Properties())); assertEquals(ForgeSettings.DEFAULTS, this.read("[main_thread]\n")); - assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10)), ForgeSettings.DEFAULTS); + assertEquals(new ForgeSettings(Duration.ofMillis(2), Duration.ofSeconds(10), Set.of()), ForgeSettings.DEFAULTS); + assertFalse(ForgeSettings.DEFAULTS.enabled(Feature.EXPERIMENTAL_PERFORMANCE)); } @Test void readsEveryKey() throws Exception { assertEquals( - new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0)), - this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n") + new ForgeSettings(Duration.ofMillis(5), Duration.ofSeconds(0), Set.of(Feature.EXPERIMENTAL_PERFORMANCE)), + this.read("[main_thread]\nbudget_ms = 5\n\n[shutdown]\ntimeout_s = 0\n\n[features]\nexperimental_performance = true\n") ); } @@ -52,4 +70,50 @@ class ForgeSettingsTest IllegalArgumentException type = assertThrows(IllegalArgumentException.class, () -> this.read("[shutdown]\ntimeout_s = \"10\"\n")); assertEquals("'shutdown.timeout_s' must be an integer, found \"10\".", type.getMessage()); } + + @Test + void featuresAreOffUnlessSwitchedOn() throws Exception + { + assertFalse(this.read("[features]\nexperimental_performance = false\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE)); + assertTrue(this.read("[features]\nexperimental_performance = true\n").enabled(Feature.EXPERIMENTAL_PERFORMANCE)); + } + + @Test + void systemPropertyTakesPrecedenceOverTheFile() throws Exception + { + String property = Feature.EXPERIMENTAL_PERFORMANCE.property(); + + assertTrue(this.read("", ForgeSettingsTest.properties(property, "true")).enabled(Feature.EXPERIMENTAL_PERFORMANCE)); + assertTrue(this.read("[features]\nexperimental_performance = false\n", ForgeSettingsTest.properties(property, "TRUE")).enabled(Feature.EXPERIMENTAL_PERFORMANCE)); + assertFalse(this.read("[features]\nexperimental_performance = true\n", ForgeSettingsTest.properties(property, "false")).enabled(Feature.EXPERIMENTAL_PERFORMANCE)); + } + + @Test + void systemPropertyAppliesWithoutFile() + { + Properties properties = ForgeSettingsTest.properties(Feature.EXPERIMENTAL_PERFORMANCE.property(), "true"); + + assertTrue(ForgeSettings.read(this.directory.resolve(ForgeSettings.FILE), properties).enabled(Feature.EXPERIMENTAL_PERFORMANCE)); + } + + @Test + void reportsUnknownFeaturesAndInvalidPropertyValues() + { + IllegalArgumentException key = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nexperimental_performance = \"yes\"\nfaster = true\n")); + assertEquals("'features.experimental_performance' must be true or false, found \"yes\".", key.getMessage()); + + IllegalArgumentException unknown = assertThrows(IllegalArgumentException.class, () -> this.read("[features]\nfaster = true\n")); + assertEquals("Unknown key 'features.faster'.", unknown.getMessage()); + + Properties properties = ForgeSettingsTest.properties( + "zomboidforge.features.faster", "true", + Feature.EXPERIMENTAL_PERFORMANCE.property(), "yes", + "zomboidforge.dir", "/forge" + ); + IllegalArgumentException property = assertThrows(IllegalArgumentException.class, () -> this.read("", properties)); + assertEquals( + "System property 'zomboidforge.features.experimental_performance' must be true or false, found \"yes\". Unknown system property 'zomboidforge.features.faster'.", + property.getMessage() + ); + } } diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index df94836..292300e 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -49,6 +49,11 @@ # Maintenance # SOFT_RESET true: start in Project Zomboid's soft reset mode (-Dsoftreset). # Intended for a single start; unset it afterwards. +# +# ZomboidForge features (also /forge/forge.toml [features]; a set variable takes precedence) +# ZF_EXPERIMENTAL_PERFORMANCE +# true/false: performance changes that alter timing or resource use +# (more threads, shorter waits). Default: false set -o errexit set -o nounset @@ -86,6 +91,9 @@ readonly SERVER_DB="${DATA_DIR}/db/${SERVER_NAME}.db" # Target of the /opt/pz/steamapps symlink; Steam stores Workshop downloads there. readonly STEAMAPPS_DIR="${DATA_DIR}/steamapps" readonly CGROUP_MEMORY_MAX="/sys/fs/cgroup/memory.max" +# Keys of the ZomboidForge features (core/config/Feature): ZF_ becomes +# -Dzomboidforge.features.. +readonly FEATURES=(experimental_performance) readonly UNLIMITED_MAX_HEAP="8g" log() { @@ -272,6 +280,30 @@ default_max_heap() { echo "$(( limit * 3 / 4 / 1024 / 1024 ))m" } +# Appends -Dzomboidforge.features.=true|false for every feature whose ZF_ is set. +# Unset or empty: no property, so forge.toml or the default (off) decides. +add_feature_properties() { + local key + local variable + local value + + for key in "${FEATURES[@]}"; do + variable="ZF_${key^^}" + value="${!variable:-}" + + if [[ -z "${value}" ]]; then + continue + fi + if is_true "${value}"; then + jvm_args+=("-Dzomboidforge.features.${key}=true") + elif is_false "${value}"; then + jvm_args+=("-Dzomboidforge.features.${key}=false") + else + fail "${variable} must be true or false, got '${value}'." + fi + done +} + # Same JVM setup as the vanilla ProjectZomboid64.json and start-server.sh. # Java runs directly instead of through the native ProjectZomboid64 launcher. build_jvm_args() { @@ -308,6 +340,7 @@ build_jvm_args() { log "SOFT_RESET is set: starting in soft reset mode. Unset it for the next start." jvm_args+=("-Dsoftreset") fi + add_feature_properties } build_server_args() {