Enhance transactional support with savepoints, improve error handling for nested exceptions, and provide better rollback mechanisms. Update tests to validate savepoint behavior and add new test cases for mod errors, task execution, and server configuration. Expand Gradle tasks to generate admin passwords, preserve configs during deployment, and support custom server addresses.

This commit is contained in:
Overlord committed 2026-10-03 01:10:38 +02:00
1 parent 26ca1b90a2
commit 67530d35e9
14 files changed
+251 -32

No files matched your search

@@ -75,7 +75,7 @@ public final class ServerHooks
ForgeInstance.FORGE.started();
System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ").");
}
catch (RuntimeException e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
/**
@@ -87,7 +87,7 @@ public final class ServerHooks
public static void onTick()
{
try { ForgeInstance.FORGE.tick(); }
catch (RuntimeException e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
/**
@@ -105,6 +105,6 @@ public final class ServerHooks
System.out.println("[ZomboidForge] Server stopping.");
ForgeInstance.FORGE.stopping();
}
catch (RuntimeException e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
}
@@ -20,6 +20,6 @@ public final class StorageHooks
if (running) ForgeInstance.FORGE.backupStarted();
else ForgeInstance.FORGE.backupFinished();
}
catch (RuntimeException e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
}
@@ -154,14 +154,17 @@ public final class Forge
);
}
/** Calls {@link Mod#onServerStarted()} of every mod in load order. Main thread. */
/**
* 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 (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", e); }
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); }
}
}
@@ -205,19 +208,25 @@ public final class Forge
/**
* 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.
* 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 (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", e); }
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
@@ -79,6 +79,8 @@ public final class MainThreadQueue
int index = count == 0 ? 0 : this.next % count;
int empty = 0;
try
{
while (empty < count && !this.closed)
{
ModQueue queue = queues[index];
@@ -96,9 +98,12 @@ public final class MainThreadQueue
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()
@@ -25,8 +25,8 @@ final class ModTaskEvent extends jdk.jfr.Event
/**
* Runs {@code action} as a {@code zomboidforge.ModTask} event. Mod code must not end the
* calling thread's work, so failures are returned instead of thrown: runtime exceptions,
* missing classes or members ({@link LinkageError}), and stack overflows.
* 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
*/
@@ -40,9 +40,9 @@ final class ModTaskEvent extends jdk.jfr.Event
action.run();
return null;
}
catch (RuntimeException | LinkageError | StackOverflowError e)
catch (Throwable t)
{
return e;
return t;
}
finally
{
@@ -10,6 +10,7 @@ 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.util.concurrent.locks.ReentrantLock;
import java.util.function.BooleanSupplier;
@@ -104,8 +105,10 @@ public final class StorageDatabase implements AutoCloseable
}
/**
* Runs {@code work} in a transaction. Nested calls on the same thread join the outer
* transaction; it commits when the outermost call returns and rolls back when any throws.
* 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)
{
@@ -118,19 +121,23 @@ public final class StorageDatabase implements AutoCloseable
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 (outermost) connection.commit();
if (savepoint == null) connection.commit();
else connection.releaseSavepoint(savepoint);
return result;
}
catch (SQLException | RuntimeException | Error e)
catch (Throwable t)
{
if (outermost) StorageDatabase.rollback(connection, e);
throw e;
StorageDatabase.rollback(connection, savepoint, t);
throw t;
}
finally
{
@@ -241,9 +248,21 @@ public final class StorageDatabase implements AutoCloseable
return connection;
}
private static void rollback(Connection connection, Throwable cause)
/** 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 { connection.rollback(); }
catch (SQLException e) { cause.addSuppressed(e); }
try
{
if (savepoint == null) {
connection.rollback();
} else {
connection.rollback(savepoint);
connection.releaseSavepoint(savepoint);
}
}
catch (SQLException e)
{
cause.addSuppressed(e);
}
}
}
@@ -12,6 +12,7 @@ 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;
@@ -197,6 +198,25 @@ class ForgeTest
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
{
@@ -152,6 +152,22 @@ class MainThreadQueueTest
assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.IllegalStateException: executed)"), this.logger.messages);
}
@Test
void logsErrorsOfTasksAndRunsTheNextTask() throws Exception
{
MainThread a = this.queue.forMod("a", this.logger);
MainThreadQueueTest.fromOtherThread(() -> {
a.execute(() -> { throw new AssertionError("failed"); });
a.execute(() -> this.ran.add("next"));
});
this.queue.drain();
assertEquals(List.of("next"), this.ran);
assertEquals(List.of("ERROR: A main-thread task threw. (java.lang.AssertionError: failed)"), this.logger.messages);
}
@Test
void closeCancelsQueuedTasksAndRejectsNewOnes() throws Exception
{
@@ -140,6 +140,50 @@ class ModTablesTest
assertEquals(9, sum);
}
@Test
void rollsBackAFailedNestedTransactionThatTheOuterOneCatches()
{
ModStorage storage = this.storage("shop");
Table<Balance> balances = storage.table("balances", Balance.class);
storage.transaction(() -> {
balances.set("a", new Balance(1));
assertThrows(IllegalStateException.class, () -> storage.transaction(() -> {
balances.set("a", new Balance(100));
balances.set("b", new Balance(100));
throw new IllegalStateException("abort");
}));
balances.set("c", new Balance(3));
});
assertEquals(Optional.of(new Balance(1)), balances.get("a"));
assertFalse(balances.contains("b"));
assertEquals(Optional.of(new Balance(3)), balances.get("c"));
}
@Test
void rollsBackForErrorsAndUndeclaredCheckedExceptions()
{
ModStorage storage = this.storage("shop");
Table<Balance> balances = storage.table("balances", Balance.class);
assertThrows(AssertionError.class, () -> storage.transaction(() -> {
balances.set("a", new Balance(1));
throw new AssertionError("abort");
}));
assertThrows(Exception.class, () -> storage.transaction(() -> {
balances.set("b", new Balance(1));
ModTablesTest.sneakyThrow(new Exception("abort"));
}));
assertEquals(0, balances.count());
}
@SuppressWarnings("unchecked")
private static <E extends Throwable> void sneakyThrow(Throwable t) throws E { throw (E) t; }
@Test
void keepsModsApart()
{
+16
View File
@@ -0,0 +1,16 @@
package testmods;
import dev.overlord.zomboidforge.api.Mod;
/**
* Entry point that tests package into a mod jar. Its lifecycle methods throw errors, which aren't
* {@link RuntimeException}.
*/
public final class ErrorMod extends Mod
{
@Override
public void onServerStarted() { throw new AssertionError("started"); }
@Override
public void onStopping() { throw new NoClassDefFoundError("stopping"); }
}
@@ -3,6 +3,7 @@ package dev.overlord.zomboidforge.gradle;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.Internal;
@@ -15,6 +16,13 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@@ -37,6 +45,8 @@ public abstract class RunServer extends DefaultTask
/** Seconds the server gets to save the world after a stop request. */
private static final int STOP_TIMEOUT = 120;
private static final SecureRandom RANDOM = new SecureRandom();
/** Contains one folder per mod, as in {@code <forge>/mods}. */
@Internal
public abstract DirectoryProperty getModsDirectory();
@@ -50,9 +60,17 @@ public abstract class RunServer extends DefaultTask
@Input
public abstract Property<String> getDataVolume();
@Input
/** Not an input, so it is not stored in the task history. */
@Internal
public abstract Property<String> getAdminPassword();
/** Holds the generated admin password of the volume when {@link #getAdminPassword()} is not set. */
@Internal
public abstract RegularFileProperty getAdminPasswordFile();
@Input
public abstract Property<String> getServerAddress();
@Input
@Optional
public abstract Property<String> getContainerEngine();
@@ -62,21 +80,26 @@ public abstract class RunServer extends DefaultTask
{
String engine = Executables.containerEngine(this.getContainerEngine().getOrNull());
String name = this.getContainerName().get();
String address = this.getServerAddress().get();
// ADMIN_PASSWORD without a value takes the value from the engine's environment, so it is not in the command line.
List<String> command = List.of(
engine, "run", "--rm",
"--name", name,
"--publish", "16261:16261/udp",
"--publish", "16262:16262/udp",
"--env", "ADMIN_PASSWORD=" + this.getAdminPassword().get(),
"--publish", address + ":16261:16261/udp",
"--publish", address + ":16262:16262/udp",
"--env", "ADMIN_PASSWORD",
"--volume", this.getDataVolume().get() + ":/data",
"--volume", this.getModsDirectory().get().getAsFile().getAbsolutePath() + ":/forge/mods:ro,Z",
this.getImage().get()
);
this.getLogger().lifecycle("Starting {} with the mod; connect to localhost:16261. Cancel the build (Ctrl+C) to stop the server.", this.getImage().get());
ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true);
builder.environment().put("ADMIN_PASSWORD", this.adminPassword());
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
this.getLogger().lifecycle("Starting {} with the mod on {}:16261. Cancel the build (Ctrl+C) to stop the server.", this.getImage().get(), address);
Process process = builder.start();
Thread output = new Thread(() -> RunServer.forward(process), "runServer output");
output.setDaemon(true);
@@ -96,6 +119,42 @@ public abstract class RunServer extends DefaultTask
}
}
/**
* The configured admin password, else the one in {@link #getAdminPasswordFile()}; a random one
* is generated into the file when it does not exist. The server uses the password only when it
* creates the admin account on the volume's first start.
*/
private String adminPassword() throws IOException
{
String configured = this.getAdminPassword().getOrNull();
if (configured != null) return configured;
Path file = this.getAdminPasswordFile().get().getAsFile().toPath();
if (Files.exists(file)) return Files.readString(file, StandardCharsets.UTF_8).strip();
byte[] random = new byte[18];
RunServer.RANDOM.nextBytes(random);
String password = Base64.getUrlEncoder().withoutPadding().encodeToString(random);
Files.createDirectories(file.getParent());
Files.writeString(file, password, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
RunServer.restrictToOwner(file);
this.getLogger().lifecycle("Generated the admin password '{}' for '{}', kept in '{}'.", password, this.getDataVolume().get(), file);
return password;
}
/** Makes {@code file} readable and writable by its owner only, where the file system has POSIX permissions. */
private static void restrictToOwner(Path file) throws IOException
{
if (!Files.getFileStore(file).supportsFileAttributeView(PosixFileAttributeView.class)) return;
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("rw-------"));
}
/** Copies the container's output to the build output, line by line. */
private static void forward(Process process)
{
@@ -64,9 +64,16 @@ public abstract class ZomboidForgeExtension
/** Image for {@code runServer}. Default: the ZomboidForge image tagged "latest". */
public abstract Property<String> getServerImage();
/** Admin password of the {@code runServer} server. Default: "admin". */
/**
* Admin password of the {@code runServer} server, used when its volume is created. Default:
* a random password, generated once per volume and kept in
* {@code <Gradle user home>/zomboidforge/admin-passwords/<volume>}.
*/
public abstract Property<String> getAdminPassword();
/** Host address {@code runServer} publishes the game ports on. Default: "127.0.0.1" (this machine only); "0.0.0.0" for every interface. */
public abstract Property<String> getServerAddress();
/** Volume for the {@code runServer} server's /data (world, config). Default: "zomboidforge-<id>". */
public abstract Property<String> getDataVolume();
@@ -55,6 +55,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
private static final String TOOLS = "dev.overlord.zomboidforge:mod-tools:";
private static final String TOOLS_MAIN = "dev.overlord.zomboidforge.tools.ModCheck";
private static final String DEFAULT_IMAGE = "git.security-command.org/overlord/zomboidforge:latest";
private static final String MOD_CONFIG = "config.toml";
private static final int JAVA = 25;
@Override
@@ -72,7 +73,7 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
extension.getApi().convention(version);
extension.getSteamBranch().convention("public");
extension.getServerImage().convention(ZomboidForgeModPlugin.DEFAULT_IMAGE);
extension.getAdminPassword().convention("admin");
extension.getServerAddress().convention("127.0.0.1");
extension.getDataVolume().convention(extension.getId().map(id -> "zomboidforge-" + id));
extension.getGameJar().convention(layout.file(project.getProviders().gradleProperty("zomboidforge.gameJar").map(File::new)));
@@ -220,6 +221,8 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
project.getTasks().named(LifecycleBasePlugin.ASSEMBLE_TASK_NAME, task -> task.dependsOn(modFolder, modZip));
// Trying the mod.
File passwords = new File(project.getGradle().getGradleUserHomeDir(), "zomboidforge/admin-passwords");
project.getTasks().register("runServer", RunServer.class, task ->
{
task.setGroup(ZomboidForgeModPlugin.GROUP);
@@ -230,14 +233,17 @@ public final class ZomboidForgeModPlugin implements Plugin<Project>
task.getContainerName().set(id.map(name -> "zomboidforge-" + name));
task.getDataVolume().set(extension.getDataVolume());
task.getAdminPassword().set(extension.getAdminPassword());
task.getAdminPasswordFile().set(layout.file(extension.getDataVolume().map(volume -> new File(passwords, volume))));
task.getServerAddress().set(extension.getServerAddress());
task.getContainerEngine().set(extension.getContainerEngine());
});
project.getTasks().register("deployMod", Sync.class, task ->
{
task.setGroup(ZomboidForgeModPlugin.GROUP);
task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory).");
task.setDescription("Copies the mod folder into zomboidForge.deployDirectory (a server's mods directory); keeps the server's config.toml of the mod.");
task.from(modFolder);
task.preserve(filter -> filter.include(ZomboidForgeModPlugin.MOD_CONFIG));
task.into(extension.getDeployDirectory().dir(id).orElse(layout.getBuildDirectory().dir("deploy-not-configured")));
task.onlyIf("zomboidForge.deployDirectory is set", element -> extension.getDeployDirectory().isPresent());
});
@@ -22,6 +22,7 @@ import java.util.jar.JarOutputStream;
import java.util.zip.ZipFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.objectweb.asm.Opcodes.ACC_FINAL;
import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
@@ -140,6 +141,23 @@ class ZomboidForgeModPluginTest
assertEquals(TaskOutcome.UP_TO_DATE, again.task(":checkMod").getOutcome());
}
@Test
void deployReplacesTheModButKeepsTheServerSettings() throws IOException
{
this.modProject(" deployDirectory = layout.projectDirectory.dir(\"server/mods\")", "");
Path deployed = this.project.resolve("server/mods/shop");
this.write("server/mods/shop/config.toml", "limit = 7\n");
this.write("server/mods/shop/lib/old.jar", "");
this.runner("deployMod").build();
assertTrue(Files.isRegularFile(deployed.resolve("shop.jar")));
assertTrue(Files.isRegularFile(deployed.resolve("lib/util.jar")));
assertFalse(Files.exists(deployed.resolve("lib/old.jar")), "files the mod no longer has are removed");
assertEquals("limit = 7\n", Files.readString(deployed.resolve("config.toml")));
}
@Test
void checksAGameModAgainstTheGameJar() throws IOException
{