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:
1 parent
26ca1b90a2
commit
67530d35e9
14 files changed
+271
-52
No files matched your search
@@ -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); }
|
||||
try { mod.mod().onServerStarted(); }
|
||||
catch (Throwable t) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onServerStarted() threw.", t); }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,18 +208,24 @@ 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;
|
||||
|
||||
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); }
|
||||
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());
|
||||
}
|
||||
|
||||
this.stopMods(this.settings.shutdownTimeout());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -79,25 +79,30 @@ public final class MainThreadQueue
|
||||
int index = count == 0 ? 0 : this.next % count;
|
||||
int empty = 0;
|
||||
|
||||
while (empty < count && !this.closed)
|
||||
try
|
||||
{
|
||||
ModQueue queue = queues[index];
|
||||
index = (index + 1) % count;
|
||||
while (empty < count && !this.closed)
|
||||
{
|
||||
ModQueue queue = queues[index];
|
||||
index = (index + 1) % count;
|
||||
|
||||
Task task = queue.tasks.poll();
|
||||
Task task = queue.tasks.poll();
|
||||
|
||||
if (task == null) {
|
||||
empty++;
|
||||
continue;
|
||||
if (task == null) {
|
||||
empty++;
|
||||
continue;
|
||||
}
|
||||
|
||||
empty = 0;
|
||||
queue.run(task.action());
|
||||
|
||||
if (System.nanoTime() >= deadline) break;
|
||||
}
|
||||
|
||||
empty = 0;
|
||||
queue.run(task.action());
|
||||
|
||||
if (System.nanoTime() >= deadline) break;
|
||||
}
|
||||
|
||||
this.next = index;
|
||||
finally
|
||||
{
|
||||
this.next = index;
|
||||
}
|
||||
}
|
||||
|
||||
/** Rejects further tasks and cancels the queued ones (their futures are cancelled). Any thread. */
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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"); }
|
||||
}
|
||||
Reference in new issue
Block a user