feat(server): write only the character rows that changed (#86)

* feat(server): add a row delta helper for incremental table writes

* feat(server): write only the character rows that changed
This commit is contained in:
Fiereu authored and GitHub committed 2026-08-03 16:35:10 +02:00
1 parent 19fc05beba
commit f01f411741
8 files changed
+281 -21

No files matched your search

@@ -8,6 +8,9 @@ import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.db.game.tables.records.CharacterFlagsRecord
import de.fiereu.openmmo.db.game.tables.records.CharacterItemsRecord
import de.fiereu.openmmo.db.game.tables.records.CharacterVarsRecord
import de.fiereu.openmmo.db.game.tables.records.CharactersRecord
import de.fiereu.openmmo.db.game.tables.records.PokemonRecord
import de.fiereu.openmmo.db.game.tables.references.CHARACTERS
@@ -29,7 +32,8 @@ interface CharacterRepository {
suspend fun insertAggregate(stored: StoredCharacter)
suspend fun saveAggregate(stored: StoredCharacter)
/** A null [previous] writes every row. */
suspend fun saveChanges(previous: StoredCharacter?, current: StoredCharacter)
/** Deletes a character owned by the user. */
suspend fun deleteById(userId: Int, id: Long): Boolean
@@ -57,16 +61,9 @@ constructor(
override suspend fun insertAggregate(stored: StoredCharacter) =
withContext(dispatcher) { dsl.transaction { cfg -> insert(cfg.dsl(), stored) } }
/** Replaces the whole aggregate. The character delete cascades to pokemon and items. */
// TODO Split the dirty tracking so a character-only change updates just the characters row
// instead of rewriting every pokemon and item row.
override suspend fun saveAggregate(stored: StoredCharacter) =
override suspend fun saveChanges(previous: StoredCharacter?, current: StoredCharacter) =
withContext(dispatcher) {
dsl.transaction { cfg ->
val tx = cfg.dsl()
tx.deleteFrom(CHARACTERS).where(CHARACTERS.ID.eq(stored.info.id)).execute()
insert(tx, stored)
}
dsl.transaction { cfg -> writeChanges(cfg.dsl(), previous, current) }
}
override suspend fun deleteById(userId: Int, id: Long): Boolean =
@@ -77,6 +74,47 @@ constructor(
.execute() == 1
}
private fun writeChanges(
tx: DSLContext,
previous: StoredCharacter?,
current: StoredCharacter,
) {
val id = current.info.id
tx.writeDelta(
CHARACTERS,
rowDelta(previous?.let { mapOf(id to it.info) }.orEmpty(), mapOf(id to current.info)),
{ CHARACTERS.ID.eq(it) },
{ _, info -> info.toRecord() },
)
tx.writeDelta(
POKEMON,
rowDelta(previous.monstersById(), current.monstersById()),
{ POKEMON.ID.eq(it) },
{ _, monster -> monster.toRecord() },
)
tx.writeDelta(
CHARACTER_ITEMS,
rowDelta(previous?.items.orEmpty(), current.items),
{ CHARACTER_ITEMS.CHARACTER_ID.eq(id).and(CHARACTER_ITEMS.ITEM_ID.eq(it)) },
{ itemId, quantity -> CharacterItemsRecord(id, itemId, quantity) },
)
tx.writeDelta(
CHARACTER_FLAGS,
rowDelta(previous?.storyFlags.orEmpty(), current.storyFlags),
{ CHARACTER_FLAGS.CHARACTER_ID.eq(id).and(CHARACTER_FLAGS.FLAG_KEY.eq(it)) },
{ key, _ -> CharacterFlagsRecord(id, key) },
)
tx.writeDelta(
CHARACTER_VARS,
rowDelta(previous?.storyVars.orEmpty(), current.storyVars),
{ CHARACTER_VARS.CHARACTER_ID.eq(id).and(CHARACTER_VARS.VAR_KEY.eq(it)) },
{ key, value -> CharacterVarsRecord(id, key, value) },
)
}
private fun StoredCharacter?.monstersById(): Map<Long, Pokemon> =
this?.let { (it.pokemon + it.pcStorage).associateBy { monster -> monster.id } }.orEmpty()
private fun insert(tx: DSLContext, stored: StoredCharacter) {
tx.insertInto(CHARACTERS).set(stored.info.toRecord()).execute()
val monsters = stored.pokemon + stored.pcStorage
@@ -73,6 +73,8 @@ constructor(
private val characters = ConcurrentHashMap<Long, StoredCharacter>()
private val charactersByUser = ConcurrentHashMap<Int, CopyOnWriteArrayList<Long>>()
// The last aggregate a write succeeded for. A flush sends the difference to it.
private val persisted = ConcurrentHashMap<Long, StoredCharacter>()
private val dirtySince = ConcurrentHashMap<Long, Long>()
private val pendingUnload = ConcurrentHashMap.newKeySet<Long>()
@@ -156,6 +158,7 @@ constructor(
)
repository.insertAggregate(stored)
characters[id] = stored
persisted[id] = stored
charactersByUser.computeIfAbsent(userId) { CopyOnWriteArrayList() }.add(id)
return stored
}
@@ -188,6 +191,7 @@ constructor(
suspend fun deleteCharacter(userId: Int, characterId: Long): Boolean {
if (!repository.deleteById(userId, characterId)) return false
characters.remove(characterId)
persisted.remove(characterId)
charactersByUser[userId]?.remove(characterId)
dirtySince.remove(characterId)
pendingUnload.remove(characterId)
@@ -325,6 +329,7 @@ constructor(
private fun cache(stored: StoredCharacter): StoredCharacter {
val existing = characters.putIfAbsent(stored.info.id, stored)
if (existing == null) persisted[stored.info.id] = stored
return existing ?: stored
}
@@ -344,7 +349,9 @@ constructor(
val stored = characters[id]
if (since != null && stored != null) {
try {
repository.saveAggregate(stored)
repository.saveChanges(persisted[id], stored)
// The written instance, not the current one, so a racing mutation stays dirty.
persisted[id] = stored
} catch (e: Exception) {
log.warn(e) { "Failed to persist character $id, will retry" }
dirtySince.putIfAbsent(id, since)
@@ -361,6 +368,7 @@ constructor(
return
}
val stored = characters.remove(id) ?: return
persisted.remove(id)
charactersByUser.remove(stored.info.userId)
}
}
@@ -0,0 +1,37 @@
package de.fiereu.openmmo.server.game.storage
import org.jooq.Condition
import org.jooq.DSLContext
import org.jooq.Table
import org.jooq.UpdatableRecord
import org.jooq.impl.DSL
/** What one table has to write and drop to catch up with a newer version of the data. */
data class RowDelta<K, V>(val changed: Map<K, V>, val removed: Set<K>) {
val isEmpty: Boolean
get() = changed.isEmpty() && removed.isEmpty()
}
fun <K, V> rowDelta(before: Map<K, V>, after: Map<K, V>): RowDelta<K, V> =
RowDelta(after.filter { (key, row) -> before[key] != row }, before.keys - after.keys)
fun <K> rowDelta(before: Set<K>, after: Set<K>): RowDelta<K, Unit> =
RowDelta((after - before).associateWith {}, before - after)
/** Removed rows go first, so the changed ones can take over a freed unique slot. */
fun <K, V, R : UpdatableRecord<R>> DSLContext.writeDelta(
table: Table<R>,
delta: RowDelta<K, V>,
match: (K) -> Condition,
record: (K, V) -> R,
) {
if (delta.removed.isNotEmpty()) {
deleteFrom(table).where(DSL.or(delta.removed.map(match))).execute()
}
if (delta.changed.isEmpty()) return
// resetTouchedOnNotNull() would drop a column set back to null, leaving it never cleared.
val records = delta.changed.map { (key, row) -> record(key, row).apply { touched(true) } }
// A table that is only a primary key has nothing to set on a conflict.
val keyOnly = table.primaryKey?.fields?.size == table.fields().size
if (keyOnly) batchInsert(records).execute() else batchMerge(records).execute()
}
@@ -0,0 +1,8 @@
-- Saves update pokemon rows in place, so moving a monster between slots can pass through a state
-- where two rows share one. Upserts arbitrate on the primary key, which stays non deferrable.
DROP INDEX uq_pokemon_owner_container_slot;
ALTER TABLE pokemon
ADD CONSTRAINT uq_pokemon_owner_container_slot
UNIQUE (owner_id, container, container_slot) DEFERRABLE INITIALLY DEFERRED;
@@ -1,15 +1,21 @@
package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.DynamicWarp
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_ITEMS
import de.fiereu.openmmo.db.game.tables.references.POKEMON
import de.fiereu.openmmo.server.game.testsupport.DockerAvailable
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.annotation.EnabledIf
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldBeEmpty
import io.kotest.matchers.maps.shouldBeEmpty
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
@@ -17,6 +23,7 @@ import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import kotlinx.coroutines.Dispatchers
import org.flywaydb.core.Flyway
import org.jooq.DSLContext
import org.jooq.impl.DSL
import org.testcontainers.containers.PostgreSQLContainer
@@ -26,6 +33,7 @@ class CharacterRepositoryIT :
val container = PostgreSQLContainer<Nothing>("postgres:18")
val entityIds = EntityIdService()
lateinit var repository: JooqCharacterRepository
lateinit var dsl: DSLContext
// Postgres timestamps have microsecond precision, so nanos would not round-trip.
fun now(): LocalDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS)
@@ -110,7 +118,7 @@ class CharacterRepositoryIT :
.locations("classpath:db/migration", "classpath:db/dev")
.load()
.migrate()
val dsl = DSL.using(container.jdbcUrl, container.username, container.password)
dsl = DSL.using(container.jdbcUrl, container.username, container.password)
repository = JooqCharacterRepository(dsl, Dispatchers.IO)
}
@@ -138,27 +146,98 @@ class CharacterRepositoryIT :
repository.loadByUser(77).map { it.info.id } shouldBe listOf(mine.info.id)
}
test("saveAggregate replaces the character, pokemon, and items") {
test("saveChanges writes the character, pokemon, and items that changed") {
val stored = aggregate(userId = 90)
repository.insertAggregate(stored)
val mutated =
val kept = stored.pokemon.single()
val added = monster(stored.info.id, PokemonContainer.PARTY, 1)
val current =
stored.copy(
info = stored.info.copy(money = 999, positionX = 12),
pokemon = mutableListOf(monster(stored.info.id, PokemonContainer.PARTY, 0)),
pokemon = mutableListOf(kept.copy(hp = 3), added),
pcStorage = mutableListOf(),
items = mutableMapOf(4 to 9, 13 to 1),
)
repository.saveAggregate(mutated)
repository.saveChanges(stored, current)
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
loaded.info.money shouldBe 999
loaded.pokemon.size shouldBe 1
loaded.pokemon.single().id shouldBe mutated.pokemon.single().id
loaded.pcStorage.size shouldBe 0
loaded.info.positionX shouldBe 12
loaded.pokemon.map { it.id } shouldBe listOf(kept.id, added.id)
loaded.pokemon.first().hp shouldBe 3
loaded.pcStorage.shouldBeEmpty()
loaded.items shouldBe mapOf(4 to 9, 13 to 1)
}
test("a character only change leaves the pokemon and item rows alone") {
val stored = aggregate(userId = 93)
repository.insertAggregate(stored)
// A row that gets rewritten loses these.
dsl.update(POKEMON)
.set(POKEMON.NICKNAME, "sentinel")
.where(POKEMON.OWNER_ID.eq(stored.info.id))
.execute()
dsl.update(CHARACTER_ITEMS)
.set(CHARACTER_ITEMS.QUANTITY, 4242)
.where(CHARACTER_ITEMS.CHARACTER_ID.eq(stored.info.id))
.execute()
repository.saveChanges(stored, stored.copy(info = stored.info.copy(money = 1)))
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
loaded.info.money shouldBe 1
loaded.pokemon.single().nickname shouldBe "sentinel"
loaded.pcStorage.single().nickname shouldBe "sentinel"
loaded.items shouldBe mapOf(4 to 4242)
}
test("saveChanges drops released monsters, spent items, and cleared story state") {
val stored =
aggregate(userId = 94).let {
it.copy(storyFlags = mutableSetOf("a", "b"), storyVars = mutableMapOf("v" to 7))
}
repository.insertAggregate(stored)
val current =
stored.copy(
pokemon = mutableListOf(),
items = mutableMapOf(),
storyFlags = mutableSetOf("b"),
storyVars = mutableMapOf(),
)
repository.saveChanges(stored, current)
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
loaded.pokemon.shouldBeEmpty()
loaded.pcStorage.size shouldBe 1
loaded.items.shouldBeEmpty()
loaded.storyFlags shouldBe setOf("b")
loaded.storyVars.shouldBeEmpty()
}
test("saveChanges clears a dynamic warp") {
val stored =
aggregate(userId = 95).let {
it.copy(info = it.info.copy(dynamicWarp = DynamicWarp(1, 50, 9, 3, 10, Direction.UP)))
}
repository.insertAggregate(stored)
repository.saveChanges(stored, stored.copy(info = stored.info.copy(dynamicWarp = null)))
repository.loadById(stored.info.id).shouldNotBeNull().info.dynamicWarp.shouldBeNull()
}
test("saveChanges without a base writes every row") {
val stored = aggregate(userId = 96)
repository.saveChanges(null, stored)
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
loaded.pokemon shouldBe stored.pokemon
loaded.items shouldBe stored.items
}
test("loadById returns null for an unknown id") {
repository.loadById(entityIds.newCharacterId()).shouldBeNull()
}
@@ -133,6 +133,56 @@ class CharacterStoreCacheTest :
}
}
test("each flush diffs against the aggregate the last one wrote") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 1)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30000
store.addMoney(id, 1)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30001
}
}
test("a failed flush keeps the older base so the retry writes both changes") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 1)
repo.failNextSave = true
store.flushAll()
store.addMoney(id, 2)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30000
repo.saved[id]!!.info.money shouldBe 30003
}
}
test("a loaded character diffs against the aggregate it was loaded from") {
runTest {
val repo = FakeCharacterRepository()
val seedStore = CharacterStore(repo, EntityIdService(), backgroundScope)
val id =
seedStore.createCharacter(7, "Misty", CharacterGender.FEMALE, Region.HOENN).info.id
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
store.getOrLoadCharacter(id).shouldNotBeNull()
store.addMoney(id, 3)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30000
}
}
test("unload persists and evicts after the flush succeeds") {
runTest {
val repo = FakeCharacterRepository()
@@ -0,0 +1,38 @@
package de.fiereu.openmmo.server.game.storage
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class RowDeltaTest :
FunSpec({
test("a new key is changed") {
rowDelta(mapOf(1 to "a"), mapOf(1 to "a", 2 to "b")) shouldBe
RowDelta(mapOf(2 to "b"), emptySet())
}
test("a different value is changed") {
rowDelta(mapOf(1 to "a"), mapOf(1 to "b")) shouldBe RowDelta(mapOf(1 to "b"), emptySet())
}
test("a dropped key is removed") {
rowDelta(mapOf(1 to "a", 2 to "b"), mapOf(1 to "a")) shouldBe RowDelta(emptyMap(), setOf(2))
}
test("equal versions produce an empty delta") {
val delta = rowDelta(mapOf(1 to "a"), mapOf(1 to "a"))
delta.isEmpty shouldBe true
}
test("an empty base changes everything") {
rowDelta(emptyMap<Int, String>(), mapOf(1 to "a")) shouldBe
RowDelta(mapOf(1 to "a"), emptySet())
}
test("a key only table tracks added and dropped keys") {
rowDelta(setOf("a", "b"), setOf("b", "c")) shouldBe RowDelta(mapOf("c" to Unit), setOf("a"))
}
test("an unchanged key only table produces an empty delta") {
rowDelta(setOf("a"), setOf("a")).isEmpty shouldBe true
}
})
@@ -9,6 +9,7 @@ class FakeCharacterRepository : CharacterRepository {
val saved = ConcurrentHashMap<Long, StoredCharacter>()
val saveCount = AtomicInteger(0)
var failNextSave = false
val lastPrevious = ConcurrentHashMap<Long, StoredCharacter>()
override suspend fun loadByUser(userId: Int): List<StoredCharacter> =
saved.values.filter { it.info.userId == userId }
@@ -19,13 +20,14 @@ class FakeCharacterRepository : CharacterRepository {
saved[stored.info.id] = stored
}
override suspend fun saveAggregate(stored: StoredCharacter) {
override suspend fun saveChanges(previous: StoredCharacter?, current: StoredCharacter) {
if (failNextSave) {
failNextSave = false
throw IllegalStateException("simulated save failure")
}
saveCount.incrementAndGet()
saved[stored.info.id] = stored
previous?.let { lastPrevious[current.info.id] = it }
saved[current.info.id] = current
}
override suspend fun deleteById(userId: Int, id: Long): Boolean {