Add BackupStoragePatch to wrap save folder backups, ensuring storage writes are paused during backups. Introduce ModStorage and ModTables for per-mod database management, supporting schema migrations and table versioning. Add ForgeInstance as a static reference to server-side Forge. Include relevant tests.

This commit is contained in:
Overlord committed 2026-10-02 13:57:50 +02:00
1 parent c56046469e
commit 68cd9fc4f9
31 files changed
+2124 -42

No files matched your search

@@ -5,6 +5,7 @@ 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;
@@ -17,6 +18,8 @@ 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;
@@ -25,6 +28,7 @@ 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;
/**
@@ -51,6 +55,7 @@ public final class Forge
private volatile List<ModLoader.LoadedMod> mods = List.of();
private volatile ForgeSettings settings = ForgeSettings.DEFAULTS;
private volatile @Nullable StorageDatabase storage;
/**
* @param directory the ZomboidForge directory
@@ -87,11 +92,12 @@ public final class Forge
* {@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 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) throws ModLoadException
public void load(GameVersion game, Path gameJar, ClassLoader parent, Path storageFile) throws ModLoadException
{
Path modsDirectory = this.directory.resolve(Forge.MODS);
@@ -110,20 +116,33 @@ public final class Forge
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<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.stopThreads(Duration.ZERO);
this.stopMods(Duration.ZERO);
throw e;
}
@@ -164,9 +183,29 @@ public final class Forge
*/
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 and events (see {@link #stopThreads}). Called on the shutdown thread.
* mods' threads, events, and storage (see {@link #stopMods}). Called on the shutdown thread.
*/
public void stopping()
{
@@ -177,24 +216,42 @@ public final class Forge
catch (RuntimeException e) { this.logger.log(System.Logger.Level.ERROR, "'" + mod.descriptor().id() + "': onStopping() threw.", e); }
}
this.stopThreads(this.settings.shutdownTimeout());
this.stopMods(this.settings.shutdownTimeout());
}
/**
* Rejects further main-thread tasks and cancels the queued ones, stops event delivery, and
* gives the mods' threads {@code timeout} to finish before they are interrupted.
* 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 stopThreads(Duration timeout)
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);
return new ModServices(this.events.forMod(id, executors.modThread(), logger), this.queue.forMod(id, logger), executors.modThread(), executors.async());
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)
);
}
}
@@ -9,6 +9,7 @@ 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;
@@ -44,7 +45,8 @@ public final class ModLoader
Events events,
MainThread main,
ModThread modThread,
AsyncExecutor async
AsyncExecutor async,
ModStorage storage
) implements ModContext {}
private ModLoader() {}
@@ -90,7 +92,8 @@ public final class ModLoader
provided.events(),
provided.main(),
provided.modThread(),
provided.async()
provided.async(),
provided.storage()
);
loaded.add(new LoadedMod(descriptor, candidate.directory(), loader, ModLoader.create(descriptor, loader, context)));
@@ -44,6 +44,10 @@ public final class ModResolver
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 + ".");
@@ -4,9 +4,10 @@ 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 and event registration of one mod, created before its entry point. */
public record ModServices(Events events, MainThread main, ModThread modThread, AsyncExecutor async)
/** 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
@@ -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,347 @@
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) {}
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";
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)
{
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 " + rows.size() + " 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 + ")");
}
/** Every row of {@code physical} with all its columns, sorted by key. */
private static List<Row> rows(Connection connection, String physical) throws SQLException
{
List<Row> rows = new ArrayList<>();
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);
}
rows.add(new StoredRow(key, values));
}
}
return rows;
}
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,154 @@
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.");
arguments[i] = stored == null ? null : RecordCodec.value(column.kind(), this.types[i], stored);
}
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,249 @@
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.Statement;
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";
/** 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. Nested calls on the same thread join the outer
* transaction; it commits when the outermost call returns and rolls back when any throws.
*/
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);
this.depth++;
try
{
T result = work.run(connection);
if (outermost) connection.commit();
return result;
}
catch (SQLException | RuntimeException | Error e)
{
if (outermost) StorageDatabase.rollback(connection, e);
throw e;
}
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 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.
*
* @return a problem to log, or {@code null}
*/
public @Nullable String backupStarted()
{
this.lock.lock();
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;
}
private static void rollback(Connection connection, Throwable cause)
{
try { connection.rollback(); }
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;
@@ -42,6 +42,7 @@ class ForgeTest
private Path mods;
private Path gameJar;
private Path storageFile;
@BeforeEach
void setUp() throws IOException
@@ -49,6 +50,8 @@ class ForgeTest
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();
}
@@ -57,7 +60,7 @@ class ForgeTest
private Forge load() throws ModLoadException
{
Forge forge = this.forge();
forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader());
forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile);
return forge;
}
@@ -188,7 +191,7 @@ class ForgeTest
));
Forge forge = this.forge();
ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader()));
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());
@@ -0,0 +1,299 @@
package dev.overlord.zomboidforge.core.storage;
import dev.overlord.zomboidforge.api.storage.ModStorage;
import dev.overlord.zomboidforge.api.storage.StorageException;
import dev.overlord.zomboidforge.api.storage.Table;
import dev.overlord.zomboidforge.core.RecordingLogger;
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.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 ModTablesTest
{
private enum Mode { EASY, 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) {}
private record BalanceWithNote(long coins, @Nullable String note) {}
private record BalanceWithLevel(long coins, int level) {}
private record BalanceAsText(String coins) {}
private record Empty() {}
@TempDir
Path directory;
private final RecordingLogger logger = new RecordingLogger();
private final AtomicBoolean forbidden = new AtomicBoolean();
private Path file;
private StorageDatabase database;
@BeforeEach
void setUp()
{
this.file = this.directory.resolve("save").resolve(StorageDatabase.FILE);
this.database = new StorageDatabase(this.file, this.forbidden::get);
}
@AfterEach
void tearDown() { this.database.close(); }
private ModStorage storage(String id) { return new ModTables(id, this.database, this.logger); }
@Test
void storesEveryColumnType()
{
Table<Everything> table = this.storage("shop").table("everything", Everything.class);
Everything stored = new Everything("a", Long.MAX_VALUE, -3, 0.5, 1.5F, true, new byte[]{1, 2}, UUID.randomUUID(), Instant.parse("2026-10-02T12:00:00.123456789Z"), Mode.HARD, null);
table.set("k", stored);
Everything read = table.get("k").orElseThrow();
assertEquals(stored.text(), read.text());
assertEquals(stored.big(), read.big());
assertEquals(stored.small(), read.small());
assertEquals(stored.ratio(), read.ratio());
assertEquals(stored.factor(), read.factor());
assertEquals(stored.flag(), read.flag());
assertArrayEquals(stored.bytes(), read.bytes());
assertEquals(stored.id(), read.id());
assertEquals(stored.when(), read.when());
assertEquals(stored.mode(), read.mode());
assertEquals(null, read.optional());
assertTrue(Files.isRegularFile(this.file), "the database is created on first use");
}
@Test
void readsAndWritesRows()
{
Table<Balance> balances = this.storage("shop").table("balances", Balance.class);
balances.setAll(Map.of("b", new Balance(2), "a", new Balance(1), "c", new Balance(3)));
balances.set("a", new Balance(10));
assertEquals(Optional.of(new Balance(10)), balances.get("a"));
assertEquals(Optional.empty(), balances.get("x"));
assertEquals(Map.of("a", new Balance(10), "c", new Balance(3)), balances.getAll(List.of("a", "c", "x")));
assertTrue(balances.contains("b"));
assertEquals(List.of("a", "b", "c"), balances.keys());
assertEquals(3, balances.count());
List<String> visited = new ArrayList<>();
balances.forEach((key, balance) -> visited.add(key + "=" + balance.coins()));
assertEquals(List.of("a=10", "b=2", "c=3"), visited);
assertTrue(balances.delete("a"));
assertFalse(balances.delete("a"));
assertEquals(2, balances.deleteAll(Set.of("b", "c", "x")));
assertEquals(0, balances.count());
}
@Test
void updatesAtomicallyAndRollsBackFailedTransactions()
{
ModStorage storage = this.storage("shop");
Table<Balance> balances = storage.table("balances", Balance.class);
assertEquals(new Balance(5), balances.update("a", old -> new Balance(old.coins() + 5), () -> new Balance(0)));
assertEquals(new Balance(8), balances.update("a", old -> new Balance(old.coins() + 3), () -> new Balance(0)));
assertThrows(IllegalStateException.class, () -> storage.transaction(() -> {
balances.set("a", new Balance(100));
balances.set("b", new Balance(100));
throw new IllegalStateException("abort");
}));
assertEquals(Optional.of(new Balance(8)), balances.get("a"));
assertFalse(balances.contains("b"));
int sum = storage.transaction(() -> {
balances.set("b", new Balance(1));
return (int) (balances.get("a").orElseThrow().coins() + balances.get("b").orElseThrow().coins());
});
assertEquals(9, sum);
}
@Test
void keepsModsApart()
{
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
Table<Balance> other = this.storage("bank").table("balances", Balance.class);
assertFalse(other.contains("a"));
assertTrue(this.storage("shop").table("balances", Balance.class).contains("a"));
}
@Test
void addsNullableColumnsAndKeepsRemovedOnes()
{
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
Table<BalanceWithNote> withNote = this.storage("shop").table("balances", BalanceWithNote.class);
assertEquals(Optional.of(new BalanceWithNote(1, null)), withNote.get("a"));
withNote.set("b", new BalanceWithNote(2, "hi"));
Table<Balance> without = this.storage("shop").table("balances", Balance.class);
without.set("c", new Balance(3));
assertEquals(List.of("WARNING: 'shop' table 'balances': column 'note' is no longer in 'Balance'; its data stays in the table."), this.logger.messages);
this.storage("shop").table("balances", Balance.class);
assertEquals(1, this.logger.messages.size(), "the removal is logged once");
assertEquals(Optional.of(new BalanceWithNote(2, "hi")), this.storage("shop").table("balances", BalanceWithNote.class).get("b"), "a returning component gets its data back");
}
@Test
void needsAMigrationForNonNullColumnsAndTypeChanges()
{
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
StorageException level = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", BalanceWithLevel.class));
assertEquals("'shop' table 'balances' does not match 'BalanceWithLevel': new column 'level' cannot be null, so existing rows need a value. Raise its version and add a migration from version 1.", level.getMessage());
StorageException text = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", BalanceAsText.class));
assertEquals("'shop' table 'balances' does not match 'BalanceAsText': column 'coins' changed from coins:long:notnull to coins:string:null. Raise its version and add a migration from version 1.", text.getMessage());
}
@Test
void migratesToNewVersions()
{
this.storage("shop").table("balances", Balance.class).setAll(Map.of("a", new Balance(1), "b", new Balance(2)));
Table<BalanceWithLevel> migrated = this.storage("shop").define("balances", BalanceWithLevel.class)
.version(2)
.migrate(1, row -> new BalanceWithLevel(row.getLong("coins") * 10, row.key().equals("a") ? 1 : 2))
.open();
assertEquals(Map.of("a", new BalanceWithLevel(10, 1), "b", new BalanceWithLevel(20, 2)), migrated.getAll(List.of("a", "b")));
assertEquals(List.of("INFO: 'shop' table 'balances': migrated 2 row(s) from schema version 1 to 2."), this.logger.messages);
StorageException missing = assertThrows(StorageException.class, () -> this.storage("shop").define("balances", BalanceWithLevel.class).version(3).open());
assertEquals("'shop' table 'balances' has schema version 2, the mod declares 3 but no migration from 2.", missing.getMessage());
StorageException older = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", BalanceWithLevel.class));
assertEquals("'shop' table 'balances' has schema version 2, newer than the mod's 1.", older.getMessage());
}
@Test
void failedMigrationsChangeNothing()
{
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
assertThrows(StorageException.class, () -> this.storage("shop").define("balances", BalanceWithLevel.class)
.version(2)
.migrate(1, row -> { throw new IllegalStateException("broken"); })
.open());
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
}
@Test
void adoptsTheTablesOfPreviousIdsOnce()
{
this.storage("store").table("balances", Balance.class).set("a", new Balance(1));
ModTables.adoptPreviousIds(this.database, "shop", List.of("store"), List.of("shop"));
ModTables.adoptPreviousIds(this.database, "shop", List.of("store"), List.of("shop"));
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
assertFalse(this.storage("store").table("balances", Balance.class).contains("a"), "'store' starts empty again");
this.storage("old").table("balances", Balance.class).set("x", new Balance(1));
StorageException taken = assertThrows(StorageException.class, () -> ModTables.adoptPreviousIds(this.database, "shop", List.of("old"), List.of("shop")));
assertEquals("'shop': cannot take over the tables of 'old' [balances], because 'shop' already has tables.", taken.getMessage());
StorageException installed = assertThrows(StorageException.class, () -> ModTables.adoptPreviousIds(this.database, "shop", List.of("old"), List.of("shop", "old")));
assertEquals("'shop': 'previous_ids' contains 'old', which is installed as a mod.", installed.getMessage());
}
@Test
void createsNoDatabaseForPreviousIdsAlone()
{
ModTables.adoptPreviousIds(this.database, "shop", List.of("store"), List.of("shop"));
assertFalse(Files.exists(this.file));
}
@Test
void rejectsTheMainThreadWhileTheServerRuns()
{
Table<Balance> balances = this.storage("shop").table("balances", Balance.class);
this.forbidden.set(true);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> balances.get("a"));
assertEquals("Storage cannot be used on the main thread while the server runs; use modThread() or async().", e.getMessage());
}
@Test
void backupsPauseWritesAndCheckpoint() throws Exception
{
Table<Balance> balances = this.storage("shop").table("balances", Balance.class);
balances.set("a", new Balance(1));
assertEquals(null, this.database.backupStarted());
assertEquals(0, Files.size(this.file.resolveSibling(StorageDatabase.FILE + "-wal")), "the WAL is written into the database file");
CountDownLatch written = new CountDownLatch(1);
Thread writer = Thread.ofPlatform().start(() -> {
balances.set("b", new Balance(2));
written.countDown();
});
assertFalse(written.await(200, TimeUnit.MILLISECONDS), "writes wait during the backup");
this.database.backupFinished();
assertTrue(written.await(5, TimeUnit.SECONDS));
writer.join();
assertTrue(balances.contains("b"));
}
@Test
void rejectsBadNamesTypesAndUseAfterClose()
{
ModStorage storage = this.storage("shop");
assertThrows(IllegalArgumentException.class, () -> storage.table("Bad", Balance.class));
assertThrows(IllegalArgumentException.class, () -> storage.table("a__b", Balance.class));
record Unsupported(List<String> names) {}
StorageException type = assertThrows(StorageException.class, () -> storage.table("lists", Unsupported.class));
assertEquals("'Unsupported.names' has the type 'java.util.List', which tables cannot store.", type.getMessage());
Table<Empty> empty = storage.table("empty", Empty.class);
empty.set("a", new Empty());
assertTrue(empty.contains("a"));
this.database.close();
assertThrows(StorageException.class, () -> empty.contains("a"));
}
}