Add ModCheckTest to test runtime mod validations and entry point superclass checks. Include Gradle verification metadata for dependency integrity.

This commit is contained in:
Overlord committed 2026-10-03 09:59:47 +02:00
1 parent 18ff32b5ce
commit 6761f2d9ea
29 files changed
+1306 -72

No files matched your search

@@ -29,6 +29,9 @@ import java.util.stream.Collectors;
*
* 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
{
@@ -13,7 +13,8 @@ import java.util.regex.Pattern;
*/
public record ModVersion(int major, int minor, int patch, @Nullable String preRelease) implements Comparable<ModVersion>
{
private static final Pattern FORMAT = Pattern.compile("(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:-([0-9A-Za-z.-]+))?");
// 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)
@@ -44,6 +44,13 @@ public final class ModTables implements ModStorage
/** 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;
@@ -226,13 +233,12 @@ public final class ModTables implements ModStorage
throw new StorageException(table + " has schema version " + stored.version() + ", the mod declares " + this.version + " but no migration from " + stored.version() + ".");
String rebuilt = physical + "__migrating";
List<Row> rows = ModTables.rows(connection, physical);
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());
for (Row row : rows)
int migrated = ModTables.forEachRow(connection, physical, row ->
{
R record;
@@ -240,13 +246,13 @@ public final class ModTables implements ModStorage
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 " + rows.size() + " row(s) from schema version " + stored.version() + " to " + this.version + ".");
ModTables.this.logger.log(System.Logger.Level.INFO, table + ": migrated " + migrated + " row(s) from schema version " + stored.version() + " to " + this.version + ".");
}
}
@@ -276,10 +282,15 @@ public final class ModTables implements ModStorage
ModTables.execute(connection, "CREATE TABLE " + SqlTable.quoted(physical) + " (" + SqlTable.quoted(SqlTable.KEY) + " TEXT PRIMARY KEY NOT NULL" + definitions + ")");
}
/** Every row of {@code physical} with all its columns, sorted by key. */
private static List<Row> rows(Connection connection, String physical) throws SQLException
/**
* 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
{
List<Row> rows = new ArrayList<>();
int count = 0;
try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM " + SqlTable.quoted(physical) + " ORDER BY " + SqlTable.quoted(SqlTable.KEY)))
{
@@ -299,11 +310,12 @@ public final class ModTables implements ModStorage
else values.put(column, value instanceof Integer number ? Long.valueOf(number) : value);
}
rows.add(new StoredRow(key, values));
action.accept(new StoredRow(key, values));
count++;
}
}
return rows;
return count;
}
private static List<String> tableNames(Connection connection, String mod) throws SQLException
@@ -102,7 +102,8 @@ final class RecordCodec<R extends Record>
if (stored == null && !column.nullable())
throw new StorageException("Column '" + column.name() + "' of '" + this.type.getSimpleName() + "' is null in the database.");
arguments[i] = stored == null ? null : RecordCodec.value(column.kind(), this.types[i], stored);
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)); }
@@ -12,6 +12,8 @@ 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;
@@ -32,6 +34,9 @@ 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>
@@ -156,15 +161,30 @@ public final class StorageDatabase implements AutoCloseable
}
/**
* Blocks storage for a backup of the save folder: waits 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.
* 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()
public @Nullable String backupStarted() { return this.backupStarted(StorageDatabase.BACKUP_WAIT); }
@Nullable String backupStarted(Duration wait)
{
this.lock.lock();
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;
@@ -26,6 +26,15 @@ class ModVersionTest
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()
{
@@ -13,6 +13,7 @@ import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@@ -34,6 +35,8 @@ class ModTablesTest
{
private enum Mode { EASY, HARD }
private enum RenamedMode { SIMPLE, HARD }
private record Everything(String text, long big, int small, double ratio, float factor, boolean flag, byte[] bytes, UUID id, Instant when, Mode mode, @Nullable Long optional) {}
private record Balance(long coins) {}
@@ -46,6 +49,10 @@ class ModTablesTest
private record Empty() {}
private record Difficulty(Mode mode) {}
private record RenamedDifficulty(RenamedMode mode) {}
@TempDir
Path directory;
@@ -90,6 +97,18 @@ class ModTablesTest
assertTrue(Files.isRegularFile(this.file), "the database is created on first use");
}
@Test
void reportsUnreadableStoredValuesAsStorageExceptions()
{
this.storage("shop").table("difficulties", Difficulty.class).set("a", new Difficulty(Mode.EASY));
Table<RenamedDifficulty> renamed = this.storage("shop").table("difficulties", RenamedDifficulty.class);
StorageException e = assertThrows(StorageException.class, () -> renamed.get("a"));
assertTrue(e.getMessage().startsWith("Column 'mode' of 'RenamedDifficulty' holds 'EASY', which is not a valid 'RenamedMode': "), e.getMessage());
assertThrows(StorageException.class, () -> renamed.forEach((key, difficulty) -> {}));
}
@Test
void readsAndWritesRows()
{
@@ -321,6 +340,38 @@ class ModTablesTest
assertTrue(balances.contains("b"));
}
@Test
void backupsDoNotWaitForeverForStorage() throws Exception
{
Table<Balance> balances = this.storage("shop").table("balances", Balance.class);
balances.set("a", new Balance(1));
CountDownLatch inside = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Thread holder = Thread.ofPlatform().start(() -> this.storage("shop").transaction(() -> {
inside.countDown();
ModTablesTest.await(release);
}));
assertTrue(inside.await(5, TimeUnit.SECONDS));
String problem = this.database.backupStarted(Duration.ofSeconds(1));
assertEquals("Storage was busy for 1 s; the backup runs without pausing storage, so its copy of 'zomboidforge.db' may be incomplete.", problem);
this.database.backupFinished();
release.countDown();
holder.join();
balances.set("b", new Balance(2));
assertTrue(balances.contains("b"), "storage stays usable after the skipped pause");
}
private static void await(CountDownLatch latch)
{
try { latch.await(); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
@Test
void rejectsBadNamesTypesAndUseAfterClose()
{