Add RolesSavePerformancePatch to optimize role saving in Build 42.21. Use single SQLite transaction to reduce redundant database operations. Include hooks, tests, and integrate the patch into the performance patch set.
This commit is contained in:
1 parent
dd113961e6
commit
529e48ed5a
7 files changed
+518
-2
No files matched your search
+2
-1
@@ -31,7 +31,8 @@ public final class B42PatchSet implements PatchSet
|
||||
new WorldGenUtilsPlacementPerformancePatch(),
|
||||
new WorldGenChunkRulesPerformancePatch(),
|
||||
new BitHeaderPoolPerformancePatch(),
|
||||
new IsoChunkSaveDirectoryPerformancePatch()
|
||||
new IsoChunkSaveDirectoryPerformancePatch(),
|
||||
new RolesSavePerformancePatch()
|
||||
);
|
||||
|
||||
@Override
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.patcher.Anchor;
|
||||
import dev.overlord.zomboidforge.patcher.Hook;
|
||||
import dev.overlord.zomboidforge.patcher.MethodBody;
|
||||
import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch;
|
||||
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
/**
|
||||
* Saves the roles in one SQLite transaction. {@code Roles.save()} is renamed to
|
||||
* {@code zomboidForge$save} and wrapped:
|
||||
*
|
||||
* <pre>{@code
|
||||
* public static void save()
|
||||
* {
|
||||
* RolesHooks.beginSave();
|
||||
* try { zomboidForge$save(); }
|
||||
* finally { RolesHooks.endSave(); }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* The vanilla method writes every role and capability with its own autocommitted statement
|
||||
* ({@code ServerWorldDatabase.saveRole}, {@code saveDefaultRole}): about 250 transactions and
|
||||
* 1,000 {@code fsync}s, 1.3 s of every shutdown on a fast disk.
|
||||
*/
|
||||
public final class RolesSavePerformancePatch extends PerformancePatch
|
||||
{
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
|
||||
private static final String RENAMED = "zomboidForge$save";
|
||||
|
||||
private static final Anchor.Call ANCHOR = new Anchor.Call(
|
||||
new Anchor.Method("save", "()V"),
|
||||
"zombie/network/ServerWorldDatabase", "saveRole", "(Lzombie/characters/Role;)V"
|
||||
);
|
||||
|
||||
private static final Hook HOOK = new Hook(RolesSavePerformancePatch.HOOKS, "beginSave", "()V");
|
||||
private static final Hook END = new Hook(RolesSavePerformancePatch.HOOKS, "endSave", "()V");
|
||||
|
||||
public RolesSavePerformancePatch() {
|
||||
super("zombie/characters/Roles", RolesSavePerformancePatch.ANCHOR, RolesSavePerformancePatch.HOOK);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Override
|
||||
public boolean appliesTo(GameVersion version) { return version.matches("42.21"); }
|
||||
|
||||
@Override
|
||||
public void apply(ClassNode node)
|
||||
{
|
||||
MethodNode save = RolesSavePerformancePatch.ANCHOR.in().resolve(node);
|
||||
|
||||
MethodBody.wrap(node, save, RolesSavePerformancePatch.RENAMED, RolesSavePerformancePatch.HOOK, RolesSavePerformancePatch.END);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.perf;
|
||||
|
||||
import dev.overlord.zomboidforge.api.GameVersion;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner;
|
||||
import dev.overlord.zomboidforge.compat.b42.patches.support.PackageScan;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.tree.AbstractInsnNode;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.objectweb.asm.tree.MethodInsnNode;
|
||||
import org.objectweb.asm.tree.MethodNode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
|
||||
import static org.objectweb.asm.Opcodes.ACC_STATIC;
|
||||
import static org.objectweb.asm.Opcodes.ACONST_NULL;
|
||||
import static org.objectweb.asm.Opcodes.CHECKCAST;
|
||||
import static org.objectweb.asm.Opcodes.INVOKEVIRTUAL;
|
||||
import static org.objectweb.asm.Opcodes.RETURN;
|
||||
import static org.objectweb.asm.Opcodes.V25;
|
||||
|
||||
class RolesSavePerformancePatchTest
|
||||
{
|
||||
private static final String ROLES = "zombie/characters/Roles";
|
||||
private static final String DATABASE = "zombie/network/ServerWorldDatabase";
|
||||
private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/RolesHooks";
|
||||
|
||||
/** {@code Roles} with a reduced {@code save()}: {@code ((ServerWorldDatabase) null).saveRole(null);} */
|
||||
private static ClassNode roles()
|
||||
{
|
||||
ClassNode node = new ClassNode();
|
||||
node.visit(V25, ACC_PUBLIC, RolesSavePerformancePatchTest.ROLES, null, "java/lang/Object", null);
|
||||
|
||||
MethodVisitor save = node.visitMethod(ACC_PUBLIC | ACC_STATIC, "save", "()V", null, null);
|
||||
save.visitInsn(ACONST_NULL);
|
||||
save.visitTypeInsn(CHECKCAST, RolesSavePerformancePatchTest.DATABASE);
|
||||
save.visitInsn(ACONST_NULL);
|
||||
save.visitTypeInsn(CHECKCAST, "zombie/characters/Role");
|
||||
save.visitMethodInsn(INVOKEVIRTUAL, RolesSavePerformancePatchTest.DATABASE, "saveRole", "(Lzombie/characters/Role;)V", false);
|
||||
save.visitInsn(RETURN);
|
||||
save.visitMaxs(0, 0);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
private static List<String> calls(MethodNode method)
|
||||
{
|
||||
List<String> calls = new ArrayList<>();
|
||||
|
||||
for (AbstractInsnNode instruction : method.instructions) {
|
||||
if (instruction instanceof MethodInsnNode call) calls.add(call.owner.substring(call.owner.lastIndexOf('/') + 1) + "." + call.name);
|
||||
}
|
||||
|
||||
return calls;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorMatchesTheTarget()
|
||||
{
|
||||
new RolesSavePerformancePatch().anchor().verify(RolesSavePerformancePatchTest.roles());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wrapsSaveBetweenTheTransactionHooks()
|
||||
{
|
||||
ClassNode node = RolesSavePerformancePatchTest.roles();
|
||||
new RolesSavePerformancePatch().apply(node);
|
||||
|
||||
MethodNode save = node.methods.stream().filter(method -> method.name.equals("save")).findFirst().orElseThrow();
|
||||
MethodNode original = node.methods.stream().filter(method -> method.name.equals("zomboidForge$save")).findFirst().orElseThrow();
|
||||
|
||||
// The normal path and the exception path each end the transaction.
|
||||
assertEquals(List.of("RolesHooks.beginSave", "Roles.zomboidForge$save", "RolesHooks.endSave", "RolesHooks.endSave"), RolesSavePerformancePatchTest.calls(save));
|
||||
assertEquals(1, save.tryCatchBlocks.size());
|
||||
assertEquals(List.of("ServerWorldDatabase.saveRole"), RolesSavePerformancePatchTest.calls(original));
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchedClassIsValid() throws ClassNotFoundException
|
||||
{
|
||||
ClassNode node = RolesSavePerformancePatchTest.roles();
|
||||
new RolesSavePerformancePatch().apply(node);
|
||||
|
||||
// Initializing links the class, which runs the bytecode verifier on the wrapper.
|
||||
ClassDefiner definer = new ClassDefiner();
|
||||
definer.define(node);
|
||||
Class.forName(node.name.replace('/', '.'), true, definer);
|
||||
}
|
||||
|
||||
/** {@code HookExistenceTest} checks the patch's {@code hook()}; this is the second one it calls. */
|
||||
@Test
|
||||
void endSaveHookExistsAsPublicStaticMethod() throws IOException
|
||||
{
|
||||
ClassNode hooks = PackageScan.read(RolesSavePerformancePatchTest.HOOKS);
|
||||
|
||||
assertTrue(hooks.methods.stream().anyMatch(method ->
|
||||
method.name.equals("endSave") && method.desc.equals("()V")
|
||||
&& (method.access & ACC_PUBLIC) != 0 && (method.access & ACC_STATIC) != 0
|
||||
));
|
||||
}
|
||||
|
||||
@Test
|
||||
void appliesOnlyToVerifiedVersions()
|
||||
{
|
||||
RolesSavePerformancePatch patch = new RolesSavePerformancePatch();
|
||||
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.0")));
|
||||
assertTrue(patch.appliesTo(GameVersion.parse("42.21.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.20.3")));
|
||||
assertFalse(patch.appliesTo(GameVersion.parse("42.22.0")));
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.invoke.MethodHandles;
|
||||
import java.lang.invoke.VarHandle;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import zombie.network.ServerWorldDatabase;
|
||||
|
||||
/**
|
||||
* Hooks called by patched {@code zombie.characters.Roles} code: {@code Roles.save()} in one
|
||||
* SQLite transaction.
|
||||
*
|
||||
* <p>{@code Roles.save()} writes every role and capability with its own statement, each in its
|
||||
* own transaction on the autocommitting connection of {@code ServerWorldDatabase}: about 250
|
||||
* transactions and 1,000 {@code fsync}s at every shutdown. In one transaction the same
|
||||
* statements write the same rows. The hooks never fail the save: when the connection cannot be
|
||||
* reached or switched, the save runs in autocommit mode as in vanilla.
|
||||
*/
|
||||
public final class RolesHooks
|
||||
{
|
||||
/** {@code ServerWorldDatabase.conn}, package-private; {@code null} when it cannot be reached. */
|
||||
private static final @Nullable VarHandle CONNECTION;
|
||||
|
||||
static
|
||||
{
|
||||
VarHandle connection = null;
|
||||
try
|
||||
{
|
||||
connection = MethodHandles.privateLookupIn(ServerWorldDatabase.class, MethodHandles.lookup())
|
||||
.findVarHandle(ServerWorldDatabase.class, "conn", Connection.class);
|
||||
}
|
||||
catch (ReflectiveOperationException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: 'ServerWorldDatabase.conn' not found: " + e); }
|
||||
|
||||
CONNECTION = connection;
|
||||
}
|
||||
|
||||
/** The connection of the running save while it is in a transaction of these hooks. */
|
||||
private static @Nullable Connection transaction;
|
||||
|
||||
private RolesHooks() {}
|
||||
|
||||
/** Called before {@code Roles.save()}: switches the database connection to one transaction. */
|
||||
public static void beginSave()
|
||||
{
|
||||
if (RolesHooks.CONNECTION == null || ServerWorldDatabase.instance == null) return;
|
||||
|
||||
Connection connection = (Connection) RolesHooks.CONNECTION.get(ServerWorldDatabase.instance);
|
||||
if (connection == null) return;
|
||||
|
||||
try
|
||||
{
|
||||
if (!connection.getAutoCommit()) return;
|
||||
|
||||
connection.setAutoCommit(false);
|
||||
RolesHooks.transaction = connection;
|
||||
}
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Roles are saved without a transaction: " + e); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Called after {@code Roles.save()}, also when it threw: commits what it wrote, as autocommit
|
||||
* would have, and switches autocommit back on.
|
||||
*/
|
||||
public static void endSave()
|
||||
{
|
||||
Connection connection = RolesHooks.transaction;
|
||||
RolesHooks.transaction = null;
|
||||
if (connection == null) return;
|
||||
|
||||
try { connection.commit(); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Committing the saved roles failed: " + e); }
|
||||
finally
|
||||
{
|
||||
try { connection.setAutoCommit(true); }
|
||||
catch (SQLException e) { System.out.println("[ZomboidForge] Switching the database back to autocommit failed: " + e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package dev.overlord.zomboidforge.compat.b42.hooks;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import zombie.network.ServerWorldDatabase;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The hooks on a real SQLite database, installed as the connection of {@code ServerWorldDatabase}. */
|
||||
class RolesHooksTest
|
||||
{
|
||||
private Connection connection;
|
||||
|
||||
private void install(Connection connection) throws ReflectiveOperationException
|
||||
{
|
||||
Field field = ServerWorldDatabase.class.getDeclaredField("conn");
|
||||
field.setAccessible(true);
|
||||
field.set(ServerWorldDatabase.instance, connection);
|
||||
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void uninstall() throws ReflectiveOperationException, SQLException
|
||||
{
|
||||
this.install(null);
|
||||
}
|
||||
|
||||
private static int count(Connection connection) throws SQLException
|
||||
{
|
||||
try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM roles"))
|
||||
{
|
||||
rows.next();
|
||||
return rows.getInt(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesBetweenTheHooksBecomeVisibleTogetherAtTheEnd(@TempDir Path temp) throws Exception
|
||||
{
|
||||
String url = "jdbc:sqlite:" + temp.resolve("test.db");
|
||||
|
||||
try (Connection server = DriverManager.getConnection(url); Connection reader = DriverManager.getConnection(url))
|
||||
{
|
||||
try (Statement statement = server.createStatement()) { statement.executeUpdate("CREATE TABLE roles (name TEXT)"); }
|
||||
this.install(server);
|
||||
|
||||
RolesHooks.beginSave();
|
||||
assertFalse(server.getAutoCommit());
|
||||
|
||||
try (Statement statement = server.createStatement())
|
||||
{
|
||||
statement.executeUpdate("INSERT INTO roles VALUES ('admin')");
|
||||
statement.executeUpdate("INSERT INTO roles VALUES ('user')");
|
||||
}
|
||||
assertEquals(0, RolesHooksTest.count(reader), "Rows are visible before the end of the save.");
|
||||
|
||||
RolesHooks.endSave();
|
||||
assertTrue(server.getAutoCommit());
|
||||
assertEquals(2, RolesHooksTest.count(reader));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesAConnectionAloneThatIsAlreadyInATransaction(@TempDir Path temp) throws Exception
|
||||
{
|
||||
try (Connection server = DriverManager.getConnection("jdbc:sqlite:" + temp.resolve("test.db")))
|
||||
{
|
||||
server.setAutoCommit(false);
|
||||
this.install(server);
|
||||
|
||||
RolesHooks.beginSave();
|
||||
RolesHooks.endSave();
|
||||
|
||||
assertFalse(server.getAutoCommit());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNothingWithoutAConnection() throws ReflectiveOperationException
|
||||
{
|
||||
this.install(null);
|
||||
|
||||
RolesHooks.beginSave();
|
||||
RolesHooks.endSave();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user