diff --git a/MOD_DEVELOPMENT.md b/MOD_DEVELOPMENT.md index 43c5c21..86f40bd 100644 --- a/MOD_DEVELOPMENT.md +++ b/MOD_DEVELOPMENT.md @@ -75,6 +75,7 @@ Methods of `Mod`, usable from the constructor on (also in field initializers): | `main()` | `MainThread` | code that touches game objects | | `modThread()` | `ModThread` | the mod's own work, one task at a time | | `async()` | `AsyncExecutor` | blocking work such as HTTP calls or file I/O | +| `storage()` | `ModStorage` | the mod's tables in the world's `zomboidforge.db` | ## Threads @@ -108,6 +109,65 @@ Listeners are matched by the event's exact class. Events that carry live game ob removed after ten failures; both `onMain` and `onModThread` return a `Subscription` to remove it earlier. +## Storage + +Mod data belongs in `storage()`: tables in `zomboidforge.db`, a SQLite database in the world's +save folder. Vanilla backups include it, and deleting the world deletes it. Each mod only +reaches its own tables. + +A record declares a table's columns; each row has a `String` key: + +```java +record Balance(long coins, @Nullable Instant lastPaid) {} + +Table balances = this.storage().table("balances", Balance.class); + +balances.set("player1", new Balance(250, Instant.now())); +Optional balance = balances.get("player1"); +balances.update("player1", old -> new Balance(old.coins() + 10, Instant.now()), () -> new Balance(0, null)); + +this.storage().transaction(() -> { // all or nothing + balances.update("player1", old -> new Balance(old.coins() - 5, old.lastPaid()), () -> new Balance(0, null)); + balances.update("player2", old -> new Balance(old.coins() + 5, old.lastPaid()), () -> new Balance(0, null)); +}); +``` + +| Component type | Stored as | +|-----------------------------------|-------------------------| +| `long`, `int`, `boolean` | integer, never null | +| `double`, `float` | real number, never null | +| `Long`, `Integer`, `Boolean`, ... | the same, may be null | +| `String`, `UUID`, enums | text (enums by name) | +| `Instant` | ISO-8601 text | +| `byte[]` | blob | + +Table and column names are `snake_case`: `lastPaid` is stored as `last_paid`. + +When the record changes between versions of the mod: + +| Change | What happens | +|--------------------------------|-------------------------------------------| +| new component that may be null | added; existing rows read `null` | +| new primitive component | needs a migration | +| removed component | the column and its data stay; logged once | +| component with another type | needs a migration | + +```java +Table balances = this.storage().define("balances", Balance.class) + .version(2) + .migrate(1, row -> new Balance(row.getLong("coins"), null)) // from stored version 1 + .open(); +``` + +Things to know: + +1. Storage calls block. On the main thread they are only allowed during `onLoad`; once the + server runs they throw, so use `modThread()` or `async()`. +2. Writes commit immediately, while the world is saved periodically. After a crash, the + world goes back to its last save, but the mod data keeps later writes. +3. When a mod's id changes, list the old ids in `mod.toml` as `previous_ids`; their tables + move to the new id once. + ## Checks at startup Before any mod code runs, ZomboidForge reads every class of the mod and its libraries. The diff --git a/README.md b/README.md index e87f5e3..6aa2724 100644 --- a/README.md +++ b/README.md @@ -93,16 +93,19 @@ forge/ podman run ... -v ./forge:/forge zomboidforge ``` -- **Settings:** a missing `config.toml` is created from the mod's defaults when the folder is - writable by UID 1000; otherwise the defaults are used without a file. Keys missing from - `config.toml` take the default. -- **Switching a mod off:** `enabled = false` in the `[forge]` table of its `config.toml`. - Mods that depend on it then fail to load. -- **Failures:** a mod that cannot be loaded stops the server with exit code 1, and the log - lists every problem. Examples: a missing or too old dependency, an unsupported game - version, game classes or methods that do not exist in the running version, invalid - settings, an exception in the mod's startup code. -- **Changes** to mods and their settings take effect when the server restarts. +A mod's settings live in its `config.toml`. When the file is missing, it is created from the +mod's defaults if the folder is writable by UID 1000; otherwise the defaults are used without a +file. Keys missing from `config.toml` take the default. `enabled = false` in its `[forge]` +table switches the mod off; mods that depend on it then fail to load. + +Mods keep their data in `zomboidforge.db` in the world's save folder +(`/data/Saves/Multiplayer//`). Vanilla backups include it, and deleting the world +deletes it. + +A mod that cannot be loaded stops the server with exit code 1, and the log lists every +problem: a missing or too old dependency, an unsupported game version, game classes or methods +that do not exist in the running version, invalid settings, or an exception in the mod's +startup code. Changes to mods and their settings take effect when the server restarts. `forge.toml`, every key optional: diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java index bd6d57f..1190d9d 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/Mod.java @@ -1,6 +1,7 @@ package dev.overlord.zomboidforge.api; import dev.overlord.zomboidforge.api.internal.ModBinding; +import dev.overlord.zomboidforge.api.storage.ModStorage; import java.nio.file.Path; @@ -80,4 +81,7 @@ public abstract class Mod /** Virtual threads for blocking work such as HTTP calls or file I/O. */ protected final AsyncExecutor async() { return this.context.async(); } + + /** The mod's tables in the world's {@code zomboidforge.db}; not on the main thread once the server runs. */ + protected final ModStorage storage() { return this.context.storage(); } } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java index 089e057..5efd9ca 100644 --- a/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java +++ b/api/src/main/java/dev/overlord/zomboidforge/api/ModContext.java @@ -1,5 +1,7 @@ package dev.overlord.zomboidforge.api; +import dev.overlord.zomboidforge.api.storage.ModStorage; + import java.nio.file.Path; /** @@ -37,4 +39,7 @@ public interface ModContext /** Virtual threads for blocking work such as HTTP calls or file I/O. */ AsyncExecutor async(); + + /** The mod's tables in the world's {@code zomboidforge.db}. */ + ModStorage storage(); } diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java new file mode 100644 index 0000000..e077816 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/ModStorage.java @@ -0,0 +1,34 @@ +package dev.overlord.zomboidforge.api.storage; + +import java.util.function.Supplier; + +/** + * The mod's tables in {@code zomboidforge.db}, next to the world's save. Every table belongs to + * the mod; other mods cannot reach it. + * + *

A record declares a table's columns: {@code String}, {@code long}/{@code int}, + * {@code double}/{@code float}, {@code boolean}, {@code byte[]}, {@code UUID}, {@code Instant}, + * and enums. Primitive components cannot be null. Table and column names are {@code snake_case} + * ({@code lastPaid} is stored as {@code last_paid}). + * + *

Calls block. On the main thread they are only allowed during startup ({@code onLoad}); + * once the server runs they throw an {@link IllegalStateException}, so database I/O never costs + * tick time. Use {@code modThread()} or {@code async()}. + */ +public interface ModStorage +{ + /** Opens the table {@code name} with schema version 1 and no migrations. */ + Table table(String name, Class type); + + /** A table with a schema version and migrations; see {@link TableDefinition}. */ + TableDefinition define(String name, Class type); + + /** + * Runs {@code work} in one transaction: writes of this thread inside it are committed + * together, or not at all when {@code work} throws. + */ + void transaction(Runnable work); + + /** Like {@link #transaction(Runnable)}, returning the result of {@code work}. */ + T transaction(Supplier work); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Row.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Row.java new file mode 100644 index 0000000..23bae2c --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Row.java @@ -0,0 +1,35 @@ +package dev.overlord.zomboidforge.api.storage; + +import org.jetbrains.annotations.Nullable; + +import java.util.Set; + +/** + * One row of a table in its stored form, given to migrations: the key and the columns by + * their {@code snake_case} names. Integers and booleans are stored as {@code Long}, other + * numbers as {@code Double}, texts (also UUIDs, instants, and enum constants) as + * {@code String}, bytes as {@code byte[]}. + */ +public interface Row +{ + String key(); + + /** The names of the stored columns. */ + Set columns(); + + /** The stored value, or {@code null} when it is null. @throws IllegalArgumentException for an unknown column */ + @Nullable Object get(String column); + + @Nullable String getString(String column); + + /** @throws IllegalStateException when the value is null */ + long getLong(String column); + + /** @throws IllegalStateException when the value is null */ + double getDouble(String column); + + /** @throws IllegalStateException when the value is null */ + boolean getBoolean(String column); + + byte @Nullable [] getBytes(String column); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/StorageException.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/StorageException.java new file mode 100644 index 0000000..8a2f549 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/StorageException.java @@ -0,0 +1,14 @@ +package dev.overlord.zomboidforge.api.storage; + +import java.io.Serial; + +/** A storage operation failed: a database error, or a table that does not match its record. */ +public final class StorageException extends RuntimeException +{ + @Serial + private static final long serialVersionUID = 1L; + + public StorageException(String message) { super(message); } + + public StorageException(String message, Throwable cause) { super(message, cause); } +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java new file mode 100644 index 0000000..7064082 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/Table.java @@ -0,0 +1,52 @@ +package dev.overlord.zomboidforge.api.storage; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +/** + * Rows of type {@code R}, each under a {@code String} key. Every write commits immediately, + * unless it runs inside {@link ModStorage#transaction}. Calls block; on the main thread they + * are only allowed during startup. + */ +public interface Table +{ + /** Stores {@code value} under {@code key}, replacing an existing row. */ + void set(String key, R value); + + /** Stores every entry in one transaction. */ + void setAll(Map values); + + Optional get(String key); + + /** The rows of the given keys that exist. */ + Map getAll(Collection keys); + + boolean contains(String key); + + /** @return whether a row was removed */ + boolean delete(String key); + + /** @return the number of rows removed */ + int deleteAll(Collection keys); + + /** Every key, sorted. */ + List keys(); + + /** Calls {@code action} for every row, sorted by key, without loading all rows at once. */ + void forEach(BiConsumer action); + + long count(); + + /** + * Replaces the row under {@code key} with {@code change} applied to it, or to + * {@code initial} when there is none, in one transaction: no other write comes in between. + * + * @return the stored value + */ + R update(String key, UnaryOperator change, Supplier initial); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java new file mode 100644 index 0000000..f722528 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/TableDefinition.java @@ -0,0 +1,33 @@ +package dev.overlord.zomboidforge.api.storage; + +import java.util.function.Function; + +/** + * A table to open with a schema version and migrations: + * + *

{@code
+ * Table balances = this.storage().define("balances", Balance.class)
+ *     .version(2)
+ *     .migrate(1, row -> new Balance(row.getLong("coins"), null))
+ *     .open();
+ * }
+ */ +public interface TableDefinition +{ + /** Schema version of the record, at least 1. Default: 1. */ + TableDefinition version(int version); + + /** + * How to turn a row stored with schema version {@code from} into the current record. Needed + * when the stored version is older than {@link #version} or the record changed in a way that + * cannot be applied without data. + */ + TableDefinition migrate(int from, Function migration); + + /** + * Creates the table, or checks the stored one against the record and migrates it. + * + * @throws StorageException when the stored table does not match and no migration applies + */ + Table open(); +} diff --git a/api/src/main/java/dev/overlord/zomboidforge/api/storage/package-info.java b/api/src/main/java/dev/overlord/zomboidforge/api/storage/package-info.java new file mode 100644 index 0000000..8e9db83 --- /dev/null +++ b/api/src/main/java/dev/overlord/zomboidforge/api/storage/package-info.java @@ -0,0 +1,10 @@ +/** + * Per-world storage for mods: record tables in a SQLite database next to the save, kept + * apart by mod id. + * + * @noinspection UnstableApiUsage, RedundantSuppression + */ +@NotNullByDefault +package dev.overlord.zomboidforge.api.storage; + +import org.jetbrains.annotations.NotNullByDefault; diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java index 9cb564c..2ee7f65 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java @@ -1,13 +1,7 @@ package dev.overlord.zomboidforge.compat.b42; -import dev.overlord.zomboidforge.compat.b42.patches.ServerLoadPatch; -import dev.overlord.zomboidforge.compat.b42.patches.ServerStartedPatch; -import dev.overlord.zomboidforge.compat.b42.patches.ServerStoppingPatch; -import dev.overlord.zomboidforge.compat.b42.patches.ServerTickPatch; -import dev.overlord.zomboidforge.compat.b42.perf.IsoGameCharacterStateMachinePerformancePatch; -import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieNetworkComponentPerformancePatch; -import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieSpotChancePerformancePatch; -import dev.overlord.zomboidforge.compat.b42.perf.IsoZombieVehiclePerformancePatch; +import dev.overlord.zomboidforge.compat.b42.patches.*; +import dev.overlord.zomboidforge.compat.b42.perf.*; import dev.overlord.zomboidforge.patcher.ClassPatch; import dev.overlord.zomboidforge.patcher.PatchSet; @@ -23,6 +17,7 @@ public final class B42PatchSet implements PatchSet new ServerStartedPatch(), new ServerTickPatch(), new ServerStoppingPatch(), + new BackupStoragePatch(), new IsoZombieVehiclePerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieSpotChancePerformancePatch(), diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/BackupStoragePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/BackupStoragePatch.java new file mode 100644 index 0000000..4f04efd --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/patches/BackupStoragePatch.java @@ -0,0 +1,115 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.ClassPatch; +import dev.overlord.zomboidforge.patcher.Hook; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.LabelNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.TryCatchBlockNode; +import org.objectweb.asm.tree.VarInsnNode; + +/** + * Wraps {@code ZipBackup.makeBackupFile(String, BackupTypes)}, which zips the save folder + * including {@code zomboidforge.db}, so that storage writes wait during a backup: + * + *
{@code
+ * private static void makeBackupFile(String serverName, BackupTypes type)
+ * {
+ *     StorageHooks.backupRunning(true);
+ *     try     { zomboidForge$makeBackupFile(serverName, type); }
+ *     finally { StorageHooks.backupRunning(false); }
+ * }
+ * }
+ * + * The vanilla method is renamed to {@code zomboidForge$makeBackupFile} and stays unchanged. It + * reads the zipped files until {@code ParallelScatterZipCreator.writeTo} returns and catches its + * own exceptions, so only a wrapper around the whole method covers the entire backup. + */ +public final class BackupStoragePatch implements ClassPatch +{ + private static final String TARGET = "zombie/core/backup/ZipBackup"; + private static final String RENAMED = "zomboidForge$makeBackupFile"; + + private static final Anchor.Method ANCHOR = new Anchor.Method( + "makeBackupFile", "(Ljava/lang/String;Lzombie/core/backup/ZipBackup$BackupTypes;)V" + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks", "backupRunning", "(Z)V" + ); + + @Override + public String target() { return BackupStoragePatch.TARGET; } + @Override + public Anchor.Method anchor() { return BackupStoragePatch.ANCHOR; } + @Override + public Hook hook() { return BackupStoragePatch.HOOK; } + + @Override + public void apply(ClassNode node) + { + MethodNode original = BackupStoragePatch.ANCHOR.resolve(node); + + if ((original.access & Opcodes.ACC_STATIC) == 0) + throw new IllegalStateException("'" + node.name + "." + original.name + original.desc + "' is not static."); + + boolean taken = node.methods.stream().anyMatch(method -> method.name.equals(BackupStoragePatch.RENAMED)); + if (taken) throw new IllegalStateException("'" + node.name + "' already has a method '" + BackupStoragePatch.RENAMED + "'."); + + MethodNode wrapper = new MethodNode(original.access, original.name, original.desc, original.signature, original.exceptions.toArray(String[]::new)); + original.name = BackupStoragePatch.RENAMED; + + BackupStoragePatch.wrap(node.name, original.desc, wrapper); + node.methods.add(wrapper); + } + + /** {@code hook(true); try { renamed(args); } finally { hook(false); }} */ + private static void wrap(String owner, String desc, MethodNode wrapper) + { + Type[] arguments = Type.getArgumentTypes(desc); + int thrown = arguments.length; + LabelNode start = new LabelNode(); + LabelNode end = new LabelNode(); + LabelNode handler = new LabelNode(); + InsnList code = wrapper.instructions; + + for (Type argument : arguments) { + if (argument.getSize() != 1) throw new IllegalStateException("'" + owner + "." + BackupStoragePatch.ANCHOR.name() + desc + "' has a wide argument; the wrapper only passes one-slot arguments."); + } + + code.add(BackupStoragePatch.hook(true)); + code.add(start); + + for (int i = 0; i < arguments.length; i++) code.add(new VarInsnNode(arguments[i].getOpcode(Opcodes.ILOAD), i)); + + code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, owner, BackupStoragePatch.RENAMED, desc, false)); + code.add(end); + code.add(BackupStoragePatch.hook(false)); + code.add(new InsnNode(Opcodes.RETURN)); + + code.add(handler); + code.add(new VarInsnNode(Opcodes.ASTORE, thrown)); + code.add(BackupStoragePatch.hook(false)); + code.add(new VarInsnNode(Opcodes.ALOAD, thrown)); + code.add(new InsnNode(Opcodes.ATHROW)); + + wrapper.tryCatchBlocks.add(new TryCatchBlockNode(start, end, handler, null)); + } + + private static InsnList hook(boolean running) + { + InsnList code = new InsnList(); + + code.add(new InsnNode(running ? Opcodes.ICONST_1 : Opcodes.ICONST_0)); + code.add(new MethodInsnNode(Opcodes.INVOKESTATIC, BackupStoragePatch.HOOK.owner(), BackupStoragePatch.HOOK.name(), BackupStoragePatch.HOOK.desc(), false)); + + return code; + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/BackupStoragePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/BackupStoragePatchTest.java new file mode 100644 index 0000000..4e79de3 --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/patches/BackupStoragePatchTest.java @@ -0,0 +1,158 @@ +package dev.overlord.zomboidforge.compat.b42.patches; + +import dev.overlord.zomboidforge.compat.b42.patches.support.CallRedirect; +import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.ClassNode; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.objectweb.asm.Opcodes.ACC_PRIVATE; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.ATHROW; +import static org.objectweb.asm.Opcodes.DUP; +import static org.objectweb.asm.Opcodes.IFEQ; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.INVOKESTATIC; +import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL; +import static org.objectweb.asm.Opcodes.NEW; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class BackupStoragePatchTest +{ + private static final String ZIP_BACKUP = "zombie/core/backup/ZipBackup"; + private static final String TYPES = "zombie/core/backup/ZipBackup$BackupTypes"; + private static final String DESC = "(Ljava/lang/String;L" + BackupStoragePatchTest.TYPES + ";)V"; + private static final String CALLS = Type.getInternalName(BackupStoragePatchTest.Calls.class); + + /** Stands in for {@code StorageHooks.backupRunning(boolean)} and records the calls. */ + public static final class Calls + { + public static final List LOG = new ArrayList<>(); + + private Calls() {} + + public static void record(String call) { Calls.LOG.add(call); } + + public static void backupRunning(boolean running) { Calls.LOG.add("backupRunning " + running); } + } + + /** + * {@code ZipBackup} with the vanilla method's shape: + * + *
{@code
+     * private static void makeBackupFile(String serverName, BackupTypes type)
+     * {
+     *     if (serverName.equals("fail")) throw new IllegalStateException("zip failed");
+     *     Calls.record("backup " + serverName);
+     * }
+     * }
+ */ + private static ClassNode zipBackup() + { + ClassNode node = BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.ZIP_BACKUP); + + MethodVisitor method = node.visitMethod(ACC_PRIVATE | ACC_STATIC, "makeBackupFile", BackupStoragePatchTest.DESC, null, null); + Label normal = new Label(); + + method.visitVarInsn(ALOAD, 0); + method.visitLdcInsn("fail"); + method.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "equals", "(Ljava/lang/Object;)Z", false); + method.visitJumpInsn(IFEQ, normal); + method.visitTypeInsn(NEW, "java/lang/IllegalStateException"); + method.visitInsn(DUP); + method.visitLdcInsn("zip failed"); + method.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalStateException", "", "(Ljava/lang/String;)V", false); + method.visitInsn(ATHROW); + + method.visitLabel(normal); + method.visitVarInsn(ALOAD, 0); + method.visitMethodInsn(INVOKESTATIC, BackupStoragePatchTest.CALLS, "record", "(Ljava/lang/String;)V", false); + method.visitInsn(RETURN); + method.visitMaxs(0, 0); + + return node; + } + + private static ClassNode emptyClass(String name) + { + ClassNode node = new ClassNode(); + node.visit(V25, ACC_PUBLIC, name, null, "java/lang/Object", null); + + MethodVisitor init = node.visitMethod(ACC_PUBLIC, "", "()V", null, null); + init.visitVarInsn(ALOAD, 0); + init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(RETURN); + init.visitMaxs(0, 0); + + return node; + } + + /** Patches {@code ZipBackup}, points the hook at {@link Calls}, and returns {@code makeBackupFile}. */ + private static Method patched() throws ReflectiveOperationException + { + BackupStoragePatch patch = new BackupStoragePatch(); + ClassNode zipBackup = BackupStoragePatchTest.zipBackup(); + + patch.apply(zipBackup); + CallRedirect.redirect(zipBackup, patch.hook().owner(), patch.hook().name(), BackupStoragePatchTest.CALLS); + + ClassDefiner definer = new ClassDefiner(); + Class types = definer.define(BackupStoragePatchTest.emptyClass(BackupStoragePatchTest.TYPES)); + Class loaded = definer.define(zipBackup); + + Method method = loaded.getDeclaredMethod("makeBackupFile", String.class, types); + method.setAccessible(true); + + BackupStoragePatchTest.Calls.LOG.clear(); + return method; + } + + @Test + void anchorMatchesTheTarget() + { + new BackupStoragePatch().anchor().verify(BackupStoragePatchTest.zipBackup()); + } + + @Test + void callsTheHookAroundTheBackup() throws ReflectiveOperationException + { + BackupStoragePatchTest.patched().invoke(null, "server", null); + + assertEquals(List.of("backupRunning true", "server", "backupRunning false"), BackupStoragePatchTest.Calls.LOG); + } + + @Test + void callsTheHookAfterAFailedBackupToo() throws ReflectiveOperationException + { + Method method = BackupStoragePatchTest.patched(); + + InvocationTargetException e = assertThrows(InvocationTargetException.class, () -> method.invoke(null, "fail", null)); + + assertInstanceOf(IllegalStateException.class, e.getCause()); + assertEquals(List.of("backupRunning true", "backupRunning false"), BackupStoragePatchTest.Calls.LOG); + } + + @Test + void failsWhenTheRenamedMethodExists() + { + ClassNode zipBackup = BackupStoragePatchTest.zipBackup(); + zipBackup.visitMethod(ACC_PRIVATE | ACC_STATIC, "zomboidForge$makeBackupFile", "()V", null, null); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> new BackupStoragePatch().apply(zipBackup)); + assertEquals("'zombie/core/backup/ZipBackup' already has a method 'zomboidForge$makeBackupFile'.", e.getMessage()); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java new file mode 100644 index 0000000..fd6ee55 --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/ForgeInstance.java @@ -0,0 +1,11 @@ +package dev.overlord.zomboidforge.compat.b42; + +import dev.overlord.zomboidforge.core.Forge; + +/** The one {@link Forge} of the server, shared by the hook classes. */ +public final class ForgeInstance +{ + public static final Forge FORGE = Forge.fromSystemProperties(); + + private ForgeInstance() {} +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java index 5be7b3b..f6d1e66 100644 --- a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ServerHooks.java @@ -2,10 +2,13 @@ package dev.overlord.zomboidforge.compat.b42.hooks; import dev.overlord.zomboidforge.api.GameVersion; import dev.overlord.zomboidforge.api.ZomboidForge; -import dev.overlord.zomboidforge.core.Forge; +import dev.overlord.zomboidforge.compat.b42.ForgeInstance; +import dev.overlord.zomboidforge.core.storage.StorageDatabase; import dev.overlord.zomboidforge.core.mods.ModLoadException; +import zombie.ZomboidFileSystem; import zombie.core.Core; +import zombie.network.GameServer; import java.nio.file.Path; @@ -17,8 +20,6 @@ import java.nio.file.Path; @SuppressWarnings("CallToPrintStackTrace") public final class ServerHooks { - private static final Forge FORGE = Forge.fromSystemProperties(); - private ServerHooks() {} /** @@ -39,7 +40,10 @@ public final class ServerHooks GameVersion game = GameVersion.parse(Core.getInstance().getGameAndBuildVersion()); Path gameJar = Path.of(Core.class.getProtectionDomain().getCodeSource().getLocation().toURI()); - ServerHooks.FORGE.load(game, gameJar, ServerHooks.class.getClassLoader()); + // The save folder ZipBackup zips. getCurrentSaveDir() depends on Core.gameMode, which GameServer.main sets to "Multiplayer" only later. + Path storage = Path.of(ZomboidFileSystem.instance.getCacheDir(), "Saves", "Multiplayer", GameServer.serverName, StorageDatabase.FILE); + + ForgeInstance.FORGE.load(game, gameJar, ServerHooks.class.getClassLoader(), storage); return true; } @@ -68,7 +72,7 @@ public final class ServerHooks { try { - ServerHooks.FORGE.started(); + ForgeInstance.FORGE.started(); System.out.println("[ZomboidForge] Server started (ZomboidForge " + ZomboidForge.VERSION + ")."); } catch (RuntimeException e) { e.printStackTrace(); } @@ -82,7 +86,7 @@ public final class ServerHooks */ public static void onTick() { - try { ServerHooks.FORGE.tick(); } + try { ForgeInstance.FORGE.tick(); } catch (RuntimeException e) { e.printStackTrace(); } } @@ -99,7 +103,7 @@ public final class ServerHooks try { System.out.println("[ZomboidForge] Server stopping."); - ServerHooks.FORGE.stopping(); + ForgeInstance.FORGE.stopping(); } catch (RuntimeException e) { e.printStackTrace(); } } diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks.java new file mode 100644 index 0000000..b6e943b --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/StorageHooks.java @@ -0,0 +1,25 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import dev.overlord.zomboidforge.compat.b42.ForgeInstance; + +/** Hooks called by patched {@code zombie.core.backup.ZipBackup} code. */ +@SuppressWarnings("CallToPrintStackTrace") +public final class StorageHooks +{ + private StorageHooks() {} + + /** + * Called by the patched {@code ZipBackup.makeBackupFile} on the thread that makes the backup: + * with {@code true} before the vanilla method, with {@code false} after it, also when it threw. + * Storage writes wait in between, so the zipped {@code zomboidforge.db} is complete. + */ + public static void backupRunning(boolean running) + { + try + { + if (running) ForgeInstance.FORGE.backupStarted(); + else ForgeInstance.FORGE.backupFinished(); + } + catch (RuntimeException e) { e.printStackTrace(); } + } +} diff --git a/core/build.gradle.kts b/core/build.gradle.kts index e36c8b5..007a696 100644 --- a/core/build.gradle.kts +++ b/core/build.gradle.kts @@ -13,4 +13,11 @@ dependencies { testImplementation(platform(libs.junit.bom)) testImplementation(libs.junit.jupiter) testRuntimeOnly(libs.junit.platform.launcher) + // At runtime the game jar provides the driver. + testRuntimeOnly(libs.sqlite.jdbc) +} + +tasks.test { + // The SQLite JDBC driver loads a native library; the server runs with the same flag. + jvmArgs("--enable-native-access=ALL-UNNAMED") } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java index 7608113..b9d0ac2 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/Forge.java @@ -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 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 /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 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 ordered = ModResolver.resolve(candidates, game, this.api); + List ordered = ModResolver.resolve(candidates, game, this.api); + List 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) + ); } } diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java index 7d524eb..8e8e8ca 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModLoader.java @@ -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))); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java index 1a68189..444e8e8 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModResolver.java @@ -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 + "."); diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java index 111705b..856554f 100644 --- a/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java +++ b/core/src/main/java/dev/overlord/zomboidforge/core/mods/ModServices.java @@ -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 diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/Column.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/Column.java new file mode 100644 index 0000000..1d34fe5 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/Column.java @@ -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 columns) + { + List parts = new ArrayList<>(); + for (Column column : columns) parts.add(column.encode()); + + return String.join(",", parts); + } + + static List decode(String text) + { + List 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; + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java new file mode 100644 index 0000000..53fe1bf --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/ModTables.java @@ -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 __}, and their schemas are kept + * in {@code forge__tables}. Opening a table creates it, or compares the record with the stored + * schema: + * + *
    + *
  • a new nullable component is added as a column (existing rows read {@code null});
  • + *
  • a removed component keeps its column and data (logged once);
  • + *
  • 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.
  • + *
+ */ +public final class ModTables implements ModStorage +{ + private static final int NAME_MAX_LENGTH = 32; + + /** A stored schema. */ + private record Schema(int version, List 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 previousIds, Collection 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 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 Table table(String name, Class type) { return this.define(name, type).open(); } + + @Override + public TableDefinition define(String name, Class 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 transaction(Supplier work) { return this.database.transaction(connection -> work.get()); } + + private final class Definition implements TableDefinition + { + private final String name; + private final Class type; + private final Map> migrations = new HashMap<>(); + private int version = 1; + + private Definition(String name, Class type) + { + this.name = name; + this.type = type; + } + + @Override + public TableDefinition 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 migrate(int from, Function migration) + { + this.migrations.put(from, Objects.requireNonNull(migration, "migration")); + return this; + } + + @Override + public Table open() + { + RecordCodec 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 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 columns = new ArrayList<>(stored.columns()); + List 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 codec, String physical, Schema stored, String table) throws SQLException + { + Function 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 rows = ModTables.rows(connection, physical); + SqlTable 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 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 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 rows(Connection connection, String physical) throws SQLException + { + List 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 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 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 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(); + } + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java new file mode 100644 index 0000000..1ce412a --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/RecordCodec.java @@ -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. + * + *

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 +{ + /** 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 type; + private final List columns; + private final Class[] types; + private final MethodHandle[] accessors; + private final MethodHandle constructor; + + private RecordCodec(Class type, List 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 RecordCodec of(Class type) + { + RecordComponent[] components = type.getRecordComponents(); + List 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 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()); } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/SqlTable.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/SqlTable.java new file mode 100644 index 0000000..b7c146c --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/SqlTable.java @@ -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 "__"} 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 implements Table +{ + /** 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 codec; + private final String physical; + private final String columns; + private final String upsert; + + /** @param physical the table's name in the database, {@code __} */ + SqlTable(StorageDatabase database, RecordCodec 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 values) + { + this.database.transaction(connection -> { + try (PreparedStatement statement = connection.prepareStatement(this.upsert)) + { + for (Map.Entry 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 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 getAll(Collection keys) + { + Map found = new LinkedHashMap<>(); + + this.database.call(connection -> { + for (List 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 keys) + { + return this.database.transaction(connection -> { + int deleted = 0; + + for (List 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 keys() + { + return this.database.call(connection -> { + List 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 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 change, Supplier 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 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> batches(Collection keys) + { + List all = List.copyOf(keys); + List> 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; + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java new file mode 100644 index 0000000..9a9a529 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StorageDatabase.java @@ -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. + * + *

Meta tables, owned by the reserved id {@code forge}: + *

    + *
  • {@code forge__tables(mod, name, version, columns)}: schema of every mod table;
  • + *
  • {@code forge__migrations(mod, previous, applied_at)}: applied {@code previous_ids} + * renames.
  • + *
+ */ +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 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 call(Work 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 transaction(Work 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); } + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/StoredRow.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StoredRow.java new file mode 100644 index 0000000..dfd7fa2 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/StoredRow.java @@ -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 values; + + StoredRow(String key, Map values) + { + this.key = key; + this.values = Collections.unmodifiableMap(values); + } + + @Override + public String key() { return this.key; } + + @Override + public Set 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; + } +} diff --git a/core/src/main/java/dev/overlord/zomboidforge/core/storage/package-info.java b/core/src/main/java/dev/overlord/zomboidforge/core/storage/package-info.java new file mode 100644 index 0000000..c81d712 --- /dev/null +++ b/core/src/main/java/dev/overlord/zomboidforge/core/storage/package-info.java @@ -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; diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java index 4dcff68..0b581ba 100644 --- a/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java +++ b/core/src/test/java/dev/overlord/zomboidforge/core/ForgeTest.java @@ -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()); diff --git a/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java new file mode 100644 index 0000000..81a5959 --- /dev/null +++ b/core/src/test/java/dev/overlord/zomboidforge/core/storage/ModTablesTest.java @@ -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 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 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 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 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 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 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 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 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 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 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 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 = storage.table("empty", Empty.class); + empty.set("a", new Empty()); + assertTrue(empty.contains("a")); + + this.database.close(); + assertThrows(StorageException.class, () -> empty.contains("a")); + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c95143b..9580f83 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,11 +3,13 @@ asm = "9.10.1" junit = "6.1.3" jetbrains-annotations = "26.0.2" night-config = "3.9.0" +sqlite-jdbc = "3.48.0.0" # Same version as the SQLite JDBC driver bundled in Project Zomboid (sqlite-jdbc.properties). [libraries] #noinspection UnusedVersionCatalogEntry jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } night-config-toml = { module = "com.electronwill.night-config:toml", version.ref = "night-config" } +sqlite-jdbc = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite-jdbc" } asm = { module = "org.ow2.asm:asm", version.ref = "asm" } asm-tree = { module = "org.ow2.asm:asm-tree", version.ref = "asm" } asm-commons = { module = "org.ow2.asm:asm-commons", version.ref = "asm" }