Add BackupStoragePatch to wrap save folder backups, ensuring storage writes are paused during backups. Introduce ModStorage and ModTables for per-mod database management, supporting schema migrations and table versioning. Add ForgeInstance as a static reference to server-side Forge. Include relevant tests.
This commit is contained in:
1 parent
c56046469e
commit
68cd9fc4f9
31 files changed
+2124
-42
No files matched your search
@@ -42,6 +42,7 @@ class ForgeTest
|
||||
|
||||
private Path mods;
|
||||
private Path gameJar;
|
||||
private Path storageFile;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException
|
||||
@@ -49,6 +50,8 @@ class ForgeTest
|
||||
this.mods = Files.createDirectories(this.directory.resolve("mods"));
|
||||
this.gameJar = TestMods.gameJar(this.directory.resolve("projectzomboid.jar"));
|
||||
|
||||
this.storageFile = this.directory.resolve("Saves").resolve("Multiplayer").resolve("test").resolve("zomboidforge.db");
|
||||
|
||||
Recorder.EVENTS.clear();
|
||||
}
|
||||
|
||||
@@ -57,7 +60,7 @@ class ForgeTest
|
||||
private Forge load() throws ModLoadException
|
||||
{
|
||||
Forge forge = this.forge();
|
||||
forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader());
|
||||
forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile);
|
||||
|
||||
return forge;
|
||||
}
|
||||
@@ -188,7 +191,7 @@ class ForgeTest
|
||||
));
|
||||
|
||||
Forge forge = this.forge();
|
||||
ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader()));
|
||||
ModLoadException e = assertThrows(ModLoadException.class, () -> forge.load(ForgeTest.GAME, this.gameJar, ForgeTest.class.getClassLoader(), this.storageFile));
|
||||
|
||||
assertEquals(List.of("'broken': onLoad() threw java.lang.IllegalStateException: broken."), e.problems());
|
||||
assertEquals(Lifecycle.Phase.BOOTING, forge.phase());
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
package dev.overlord.zomboidforge.core.storage;
|
||||
|
||||
import dev.overlord.zomboidforge.api.storage.ModStorage;
|
||||
import dev.overlord.zomboidforge.api.storage.StorageException;
|
||||
import dev.overlord.zomboidforge.api.storage.Table;
|
||||
import dev.overlord.zomboidforge.core.RecordingLogger;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class ModTablesTest
|
||||
{
|
||||
private enum Mode { EASY, HARD }
|
||||
|
||||
private record Everything(String text, long big, int small, double ratio, float factor, boolean flag, byte[] bytes, UUID id, Instant when, Mode mode, @Nullable Long optional) {}
|
||||
|
||||
private record Balance(long coins) {}
|
||||
|
||||
private record BalanceWithNote(long coins, @Nullable String note) {}
|
||||
|
||||
private record BalanceWithLevel(long coins, int level) {}
|
||||
|
||||
private record BalanceAsText(String coins) {}
|
||||
|
||||
private record Empty() {}
|
||||
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
private final RecordingLogger logger = new RecordingLogger();
|
||||
private final AtomicBoolean forbidden = new AtomicBoolean();
|
||||
|
||||
private Path file;
|
||||
private StorageDatabase database;
|
||||
|
||||
@BeforeEach
|
||||
void setUp()
|
||||
{
|
||||
this.file = this.directory.resolve("save").resolve(StorageDatabase.FILE);
|
||||
this.database = new StorageDatabase(this.file, this.forbidden::get);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() { this.database.close(); }
|
||||
|
||||
private ModStorage storage(String id) { return new ModTables(id, this.database, this.logger); }
|
||||
|
||||
@Test
|
||||
void storesEveryColumnType()
|
||||
{
|
||||
Table<Everything> table = this.storage("shop").table("everything", Everything.class);
|
||||
Everything stored = new Everything("a", Long.MAX_VALUE, -3, 0.5, 1.5F, true, new byte[]{1, 2}, UUID.randomUUID(), Instant.parse("2026-10-02T12:00:00.123456789Z"), Mode.HARD, null);
|
||||
|
||||
table.set("k", stored);
|
||||
Everything read = table.get("k").orElseThrow();
|
||||
|
||||
assertEquals(stored.text(), read.text());
|
||||
assertEquals(stored.big(), read.big());
|
||||
assertEquals(stored.small(), read.small());
|
||||
assertEquals(stored.ratio(), read.ratio());
|
||||
assertEquals(stored.factor(), read.factor());
|
||||
assertEquals(stored.flag(), read.flag());
|
||||
assertArrayEquals(stored.bytes(), read.bytes());
|
||||
assertEquals(stored.id(), read.id());
|
||||
assertEquals(stored.when(), read.when());
|
||||
assertEquals(stored.mode(), read.mode());
|
||||
assertEquals(null, read.optional());
|
||||
assertTrue(Files.isRegularFile(this.file), "the database is created on first use");
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsAndWritesRows()
|
||||
{
|
||||
Table<Balance> balances = this.storage("shop").table("balances", Balance.class);
|
||||
|
||||
balances.setAll(Map.of("b", new Balance(2), "a", new Balance(1), "c", new Balance(3)));
|
||||
balances.set("a", new Balance(10));
|
||||
|
||||
assertEquals(Optional.of(new Balance(10)), balances.get("a"));
|
||||
assertEquals(Optional.empty(), balances.get("x"));
|
||||
assertEquals(Map.of("a", new Balance(10), "c", new Balance(3)), balances.getAll(List.of("a", "c", "x")));
|
||||
assertTrue(balances.contains("b"));
|
||||
assertEquals(List.of("a", "b", "c"), balances.keys());
|
||||
assertEquals(3, balances.count());
|
||||
|
||||
List<String> visited = new ArrayList<>();
|
||||
balances.forEach((key, balance) -> visited.add(key + "=" + balance.coins()));
|
||||
assertEquals(List.of("a=10", "b=2", "c=3"), visited);
|
||||
|
||||
assertTrue(balances.delete("a"));
|
||||
assertFalse(balances.delete("a"));
|
||||
assertEquals(2, balances.deleteAll(Set.of("b", "c", "x")));
|
||||
assertEquals(0, balances.count());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatesAtomicallyAndRollsBackFailedTransactions()
|
||||
{
|
||||
ModStorage storage = this.storage("shop");
|
||||
Table<Balance> balances = storage.table("balances", Balance.class);
|
||||
|
||||
assertEquals(new Balance(5), balances.update("a", old -> new Balance(old.coins() + 5), () -> new Balance(0)));
|
||||
assertEquals(new Balance(8), balances.update("a", old -> new Balance(old.coins() + 3), () -> new Balance(0)));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> storage.transaction(() -> {
|
||||
balances.set("a", new Balance(100));
|
||||
balances.set("b", new Balance(100));
|
||||
throw new IllegalStateException("abort");
|
||||
}));
|
||||
|
||||
assertEquals(Optional.of(new Balance(8)), balances.get("a"));
|
||||
assertFalse(balances.contains("b"));
|
||||
|
||||
int sum = storage.transaction(() -> {
|
||||
balances.set("b", new Balance(1));
|
||||
return (int) (balances.get("a").orElseThrow().coins() + balances.get("b").orElseThrow().coins());
|
||||
});
|
||||
assertEquals(9, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsModsApart()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
|
||||
Table<Balance> other = this.storage("bank").table("balances", Balance.class);
|
||||
|
||||
assertFalse(other.contains("a"));
|
||||
assertTrue(this.storage("shop").table("balances", Balance.class).contains("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsNullableColumnsAndKeepsRemovedOnes()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
|
||||
|
||||
Table<BalanceWithNote> withNote = this.storage("shop").table("balances", BalanceWithNote.class);
|
||||
assertEquals(Optional.of(new BalanceWithNote(1, null)), withNote.get("a"));
|
||||
withNote.set("b", new BalanceWithNote(2, "hi"));
|
||||
|
||||
Table<Balance> without = this.storage("shop").table("balances", Balance.class);
|
||||
without.set("c", new Balance(3));
|
||||
assertEquals(List.of("WARNING: 'shop' table 'balances': column 'note' is no longer in 'Balance'; its data stays in the table."), this.logger.messages);
|
||||
|
||||
this.storage("shop").table("balances", Balance.class);
|
||||
assertEquals(1, this.logger.messages.size(), "the removal is logged once");
|
||||
|
||||
assertEquals(Optional.of(new BalanceWithNote(2, "hi")), this.storage("shop").table("balances", BalanceWithNote.class).get("b"), "a returning component gets its data back");
|
||||
}
|
||||
|
||||
@Test
|
||||
void needsAMigrationForNonNullColumnsAndTypeChanges()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
|
||||
|
||||
StorageException level = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", BalanceWithLevel.class));
|
||||
assertEquals("'shop' table 'balances' does not match 'BalanceWithLevel': new column 'level' cannot be null, so existing rows need a value. Raise its version and add a migration from version 1.", level.getMessage());
|
||||
|
||||
StorageException text = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", BalanceAsText.class));
|
||||
assertEquals("'shop' table 'balances' does not match 'BalanceAsText': column 'coins' changed from coins:long:notnull to coins:string:null. Raise its version and add a migration from version 1.", text.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void migratesToNewVersions()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).setAll(Map.of("a", new Balance(1), "b", new Balance(2)));
|
||||
|
||||
Table<BalanceWithLevel> migrated = this.storage("shop").define("balances", BalanceWithLevel.class)
|
||||
.version(2)
|
||||
.migrate(1, row -> new BalanceWithLevel(row.getLong("coins") * 10, row.key().equals("a") ? 1 : 2))
|
||||
.open();
|
||||
|
||||
assertEquals(Map.of("a", new BalanceWithLevel(10, 1), "b", new BalanceWithLevel(20, 2)), migrated.getAll(List.of("a", "b")));
|
||||
assertEquals(List.of("INFO: 'shop' table 'balances': migrated 2 row(s) from schema version 1 to 2."), this.logger.messages);
|
||||
|
||||
StorageException missing = assertThrows(StorageException.class, () -> this.storage("shop").define("balances", BalanceWithLevel.class).version(3).open());
|
||||
assertEquals("'shop' table 'balances' has schema version 2, the mod declares 3 but no migration from 2.", missing.getMessage());
|
||||
|
||||
StorageException older = assertThrows(StorageException.class, () -> this.storage("shop").table("balances", BalanceWithLevel.class));
|
||||
assertEquals("'shop' table 'balances' has schema version 2, newer than the mod's 1.", older.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedMigrationsChangeNothing()
|
||||
{
|
||||
this.storage("shop").table("balances", Balance.class).set("a", new Balance(1));
|
||||
|
||||
assertThrows(StorageException.class, () -> this.storage("shop").define("balances", BalanceWithLevel.class)
|
||||
.version(2)
|
||||
.migrate(1, row -> { throw new IllegalStateException("broken"); })
|
||||
.open());
|
||||
|
||||
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adoptsTheTablesOfPreviousIdsOnce()
|
||||
{
|
||||
this.storage("store").table("balances", Balance.class).set("a", new Balance(1));
|
||||
|
||||
ModTables.adoptPreviousIds(this.database, "shop", List.of("store"), List.of("shop"));
|
||||
ModTables.adoptPreviousIds(this.database, "shop", List.of("store"), List.of("shop"));
|
||||
|
||||
assertEquals(Optional.of(new Balance(1)), this.storage("shop").table("balances", Balance.class).get("a"));
|
||||
assertFalse(this.storage("store").table("balances", Balance.class).contains("a"), "'store' starts empty again");
|
||||
|
||||
this.storage("old").table("balances", Balance.class).set("x", new Balance(1));
|
||||
|
||||
StorageException taken = assertThrows(StorageException.class, () -> ModTables.adoptPreviousIds(this.database, "shop", List.of("old"), List.of("shop")));
|
||||
assertEquals("'shop': cannot take over the tables of 'old' [balances], because 'shop' already has tables.", taken.getMessage());
|
||||
|
||||
StorageException installed = assertThrows(StorageException.class, () -> ModTables.adoptPreviousIds(this.database, "shop", List.of("old"), List.of("shop", "old")));
|
||||
assertEquals("'shop': 'previous_ids' contains 'old', which is installed as a mod.", installed.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsNoDatabaseForPreviousIdsAlone()
|
||||
{
|
||||
ModTables.adoptPreviousIds(this.database, "shop", List.of("store"), List.of("shop"));
|
||||
|
||||
assertFalse(Files.exists(this.file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsTheMainThreadWhileTheServerRuns()
|
||||
{
|
||||
Table<Balance> balances = this.storage("shop").table("balances", Balance.class);
|
||||
|
||||
this.forbidden.set(true);
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class, () -> balances.get("a"));
|
||||
assertEquals("Storage cannot be used on the main thread while the server runs; use modThread() or async().", e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void backupsPauseWritesAndCheckpoint() throws Exception
|
||||
{
|
||||
Table<Balance> balances = this.storage("shop").table("balances", Balance.class);
|
||||
balances.set("a", new Balance(1));
|
||||
|
||||
assertEquals(null, this.database.backupStarted());
|
||||
assertEquals(0, Files.size(this.file.resolveSibling(StorageDatabase.FILE + "-wal")), "the WAL is written into the database file");
|
||||
|
||||
CountDownLatch written = new CountDownLatch(1);
|
||||
Thread writer = Thread.ofPlatform().start(() -> {
|
||||
balances.set("b", new Balance(2));
|
||||
written.countDown();
|
||||
});
|
||||
|
||||
assertFalse(written.await(200, TimeUnit.MILLISECONDS), "writes wait during the backup");
|
||||
|
||||
this.database.backupFinished();
|
||||
|
||||
assertTrue(written.await(5, TimeUnit.SECONDS));
|
||||
writer.join();
|
||||
assertTrue(balances.contains("b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsBadNamesTypesAndUseAfterClose()
|
||||
{
|
||||
ModStorage storage = this.storage("shop");
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> storage.table("Bad", Balance.class));
|
||||
assertThrows(IllegalArgumentException.class, () -> storage.table("a__b", Balance.class));
|
||||
|
||||
record Unsupported(List<String> names) {}
|
||||
StorageException type = assertThrows(StorageException.class, () -> storage.table("lists", Unsupported.class));
|
||||
assertEquals("'Unsupported.names' has the type 'java.util.List', which tables cannot store.", type.getMessage());
|
||||
|
||||
Table<Empty> empty = storage.table("empty", Empty.class);
|
||||
empty.set("a", new Empty());
|
||||
assertTrue(empty.contains("a"));
|
||||
|
||||
this.database.close();
|
||||
assertThrows(StorageException.class, () -> empty.contains("a"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user