feat(server): persist accounts and characters in PostgreSQL (#48)

* feat(server): persist accounts and characters in PostgreSQL via jOOQ, HikariCP, and Flyway

* test: reword test names to match the writing style

* docs: explain the database setup and dev seeding
This commit is contained in:
Fiereu authored and GitHub committed 2026-07-21 11:25:21 +02:00
1 parent fb93eb4e5d
commit daf4daf197
50 files changed
+1622 -70

No files matched your search

@@ -2,9 +2,28 @@ package de.fiereu.openmmo.server.game
import de.fiereu.openmmo.server.game.config.ConfigLoader
import de.fiereu.openmmo.server.game.di.DaggerGameServerComponent
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
private val log = KotlinLogging.logger {}
private val SHUTDOWN_FLUSH_TIMEOUT = 10.seconds
fun main() {
val config = ConfigLoader.load()
val component = DaggerGameServerComponent.factory().create(config)
component.databaseBootstrap().migrate()
val characterStore = component.characterStore()
characterStore.startPeriodicFlush()
Runtime.getRuntime()
.addShutdownHook(
Thread {
runCatching {
runBlocking { withTimeout(SHUTDOWN_FLUSH_TIMEOUT) { characterStore.shutdown() } }
}
.onFailure { log.warn(it) { "Final character flush did not complete" } }
})
component.server().start()
}
@@ -13,6 +13,16 @@ object ConfigLoader {
checksumSize = config.getInt("server.checksumSize"),
rootKeyResource = config.getString("server.rootKeyResource"),
sessionSecret = secret.toByteArray(Charsets.UTF_8),
db =
DbConfig(
host = config.getString("db.host"),
port = config.getInt("db.port"),
name = config.getString("db.name"),
user = config.getString("db.user"),
password = config.getString("db.password"),
poolSize = config.getInt("db.poolSize"),
seedDev = config.getBoolean("db.seedDev"),
),
)
}
}
@@ -0,0 +1,14 @@
package de.fiereu.openmmo.server.game.config
data class DbConfig(
val host: String = "localhost",
val port: Int = 20021,
val name: String = "openmmo_game_db",
val user: String = "openmmo_game_user",
val password: String = "changeMe!",
val poolSize: Int = 4,
val seedDev: Boolean = true,
) {
val jdbcUrl: String
get() = "jdbc:postgresql://$host:$port/$name"
}
@@ -6,6 +6,7 @@ data class GameServerConfig(
val checksumSize: Int,
val rootKeyResource: String,
val sessionSecret: ByteArray,
val db: DbConfig = DbConfig(),
) {
override fun equals(other: Any?): Boolean =
other is GameServerConfig &&
@@ -13,7 +14,8 @@ data class GameServerConfig(
port == other.port &&
checksumSize == other.checksumSize &&
rootKeyResource == other.rootKeyResource &&
sessionSecret.contentEquals(other.sessionSecret)
sessionSecret.contentEquals(other.sessionSecret) &&
db == other.db
override fun hashCode(): Int {
var h = host.hashCode()
@@ -21,6 +23,7 @@ data class GameServerConfig(
h = h * 31 + checksumSize
h = h * 31 + rootKeyResource.hashCode()
h = h * 31 + sessionSecret.contentHashCode()
h = h * 31 + db.hashCode()
return h
}
}
@@ -0,0 +1,33 @@
package de.fiereu.openmmo.server.game.db
import de.fiereu.openmmo.server.game.config.GameServerConfig
import io.github.oshai.kotlinlogging.KotlinLogging
import javax.inject.Inject
import javax.inject.Singleton
import javax.sql.DataSource
import org.flywaydb.core.Flyway
private val log = KotlinLogging.logger {}
@Singleton
class DatabaseBootstrap
@Inject
constructor(
private val dataSource: DataSource,
private val config: GameServerConfig,
) {
fun migrate() {
val locations = buildList {
add("classpath:db/migration")
if (config.db.seedDev) add("classpath:db/dev")
}
val result =
Flyway.configure()
.dataSource(dataSource)
.locations(*locations.toTypedArray())
.load()
.migrate()
log.info { "Applied ${result.migrationsExecuted} database migrations" }
}
}
@@ -4,8 +4,10 @@ import dagger.BindsInstance
import dagger.Component
import de.fiereu.openmmo.server.game.GameServer
import de.fiereu.openmmo.server.game.config.GameServerConfig
import de.fiereu.openmmo.server.game.db.DatabaseBootstrap
import de.fiereu.openmmo.server.game.handler.GameAppHandler
import de.fiereu.openmmo.server.game.session.SessionRegistry
import de.fiereu.openmmo.server.game.storage.CharacterStore
import javax.inject.Provider
import javax.inject.Singleton
@@ -19,6 +21,10 @@ interface GameServerComponent {
fun sessionRegistry(): SessionRegistry
fun databaseBootstrap(): DatabaseBootstrap
fun characterStore(): CharacterStore
@Component.Factory
fun interface Factory {
fun create(@BindsInstance config: GameServerConfig): GameServerComponent
@@ -1,11 +1,15 @@
package de.fiereu.openmmo.server.game.di
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import dagger.Module
import dagger.Provides
import de.fiereu.openmmo.common.auth.SessionTokenVerifier
import de.fiereu.openmmo.common.io.PemKeyLoader
import de.fiereu.openmmo.common.io.resource
import de.fiereu.openmmo.server.game.config.GameServerConfig
import de.fiereu.openmmo.server.game.storage.CharacterRepository
import de.fiereu.openmmo.server.game.storage.JooqCharacterRepository
import de.fiereu.openmmo.server.game.world.interest.InterestPolicy
import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy
import io.netty.channel.EventLoopGroup
@@ -14,9 +18,14 @@ import io.netty.channel.nio.NioIoHandler
import java.security.interfaces.ECPrivateKey
import javax.inject.Named
import javax.inject.Singleton
import javax.sql.DataSource
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.jooq.DSLContext
import org.jooq.SQLDialect
import org.jooq.impl.DSL
@Module
object GameServerModule {
@@ -46,4 +55,32 @@ object GameServerModule {
fun coroutineScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@Provides @Singleton fun interestPolicy(impl: PassThroughInterestPolicy): InterestPolicy = impl
@Provides
@Singleton
fun characterRepository(impl: JooqCharacterRepository): CharacterRepository = impl
// Never touch the database while building the Dagger graph. The explicit
// migrate() call in main() is the fail-fast connection check.
@Provides
@Singleton
fun dataSource(config: GameServerConfig): DataSource =
HikariDataSource(
HikariConfig().apply {
jdbcUrl = config.db.jdbcUrl
username = config.db.user
password = config.db.password
maximumPoolSize = config.db.poolSize
initializationFailTimeout = -1
})
@Provides
@Singleton
fun dslContext(dataSource: DataSource): DSLContext = DSL.using(dataSource, SQLDialect.POSTGRES)
@Provides
@Singleton
@Named("db")
fun dbDispatcher(config: GameServerConfig): CoroutineDispatcher =
Dispatchers.IO.limitedParallelism(config.db.poolSize)
}
@@ -161,6 +161,7 @@ constructor(
if (charId != null) {
presenceService.leave(session)
sessionRegistry.unbindCharacter(charId)
characterStore.unloadCharacterAsync(charId)
}
multiplayerService.broadcastMessage(
ChatMessagePacket(
@@ -28,6 +28,7 @@ import de.fiereu.openmmo.net.game.packets.battle.BattleSwitchInPacket
import de.fiereu.openmmo.net.game.packets.battle.BattleTileMapPacket
import de.fiereu.openmmo.server.game.session.PLAYER_STATE
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService
import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap
@@ -43,7 +44,6 @@ private const val CATCH_COMMAND = "/catch"
private const val PATRAT: Short = 504
private const val WILD_MON_ID = 0x000000000003C000L
private const val CAUGHT_PATRAT_UID = 0x000000000002C000L
private const val WILD_PATRAT_HP: Short = 14
private const val CAUGHT_PATRAT_LEVEL: Byte = 2
private const val CAUGHT_PATRAT_HP: Short = 8
@@ -71,6 +71,7 @@ class BattleService
@Inject
constructor(
private val characterStore: CharacterStore,
private val entityIds: EntityIdService,
) {
private val battleTurn = ConcurrentHashMap<Long, Int>()
@@ -148,8 +149,10 @@ constructor(
battleTurn.remove(charId)
battleActiveSlot.remove(charId)
battleSeenActive.remove(charId)
val ot = characterStore.getCharacter(charId)?.info?.name ?: ""
val patrat = caughtPatrat(charId, ot)
val stored = characterStore.getCharacter(charId)
val ot = stored?.info?.name ?: ""
val nextSlot = ((stored?.pokemon?.maxOfOrNull { it.containerSlot } ?: -1) + 1).toShort()
val patrat = caughtPatrat(charId, ot, nextSlot)
// The caught Patrat is sent as a full 148-byte record on opcode 0x14 before the ball-throw
// event, so the client can resolve the monster when the throw lands.
session.send(SocialListEntryAddPacket(patrat))
@@ -186,12 +189,12 @@ constructor(
)
}
private fun caughtPatrat(ownerId: Long, ot: String): Pokemon =
private fun caughtPatrat(ownerId: Long, ot: String, slot: Short): Pokemon =
Pokemon(
id = CAUGHT_PATRAT_UID,
id = entityIds.newMonsterId(),
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 1,
containerSlot = slot,
dexId = PATRAT.toInt(),
seed = 0,
ot = ot,
@@ -98,20 +98,25 @@ constructor(
ctx.send(JoinResponsePacket.acceptNow(playtime = 1337, rewardPoints = 420, balance = 187))
}
fun onCreateCharacter(event: PacketEvent<CreateCharacterPacket>) {
suspend fun onCreateCharacter(event: PacketEvent<CreateCharacterPacket>) {
val ctx = event.session
val state = ctx.attributes[PLAYER_STATE]
if (state == null) {
log.warn { "Create character from unknown session" }
return
}
val name = event.packet.name
val name = event.packet.name.trim()
if (name.isEmpty() || name.length > 32) {
log.warn { "Rejected character name '${event.packet.name}' for userId=${state.userId}" }
ctx.send(buildCharacterList(state.userId))
return
}
log.info { "Creating character '$name' for userId=${state.userId}" }
characterStore.createCharacter(state.userId, name)
ctx.send(buildCharacterList(state.userId))
}
fun onCharacterRequest(event: PacketEvent<RequestCharactersPacket>) {
suspend fun onCharacterRequest(event: PacketEvent<RequestCharactersPacket>) {
val ctx = event.session
val state = ctx.attributes[PLAYER_STATE]
if (state != null) {
@@ -122,7 +127,7 @@ constructor(
}
}
private fun buildCharacterList(userId: Int): CharactersListPacket {
private suspend fun buildCharacterList(userId: Int): CharactersListPacket {
val characters = characterStore.getCharactersByUser(userId)
val entries =
characters.map { stored ->
@@ -136,10 +141,10 @@ constructor(
return CharactersListPacket(entries)
}
fun onCharacterSelected(event: PacketEvent<SelectCharacterPacket>) {
suspend fun onCharacterSelected(event: PacketEvent<SelectCharacterPacket>) {
val ctx = event.session
val charId = event.packet.characterId
val stored = characterStore.getCharacter(charId)
val stored = characterStore.getOrLoadCharacter(charId)
if (stored == null) {
log.warn { "Character $charId not found" }
return
@@ -179,6 +179,7 @@ constructor(
targetBank,
targetMap,
)
characterStore.flushCharacterAsync(charId)
presenceService.refresh(ctx)
mapLoadService.preloadConnectedMaps(ctx, map, depth = 1)
@@ -94,6 +94,7 @@ constructor(
positionY = offsetY.toShort(),
)
characterStore.updateCharacter(newInfo)
characterStore.flushCharacterAsync(charId)
if (state != null) {
state.regionId = warp.targetRegionId.toInt()
@@ -0,0 +1,261 @@
package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
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.common.enums.PokemonStats
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
import de.fiereu.openmmo.db.game.tables.references.CHARACTER_ITEMS
import de.fiereu.openmmo.db.game.tables.references.POKEMON
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import org.jooq.DSLContext
interface CharacterRepository {
suspend fun loadByUser(userId: Int): List<StoredCharacter>
suspend fun loadById(id: Long): StoredCharacter?
suspend fun insertAggregate(stored: StoredCharacter)
suspend fun saveAggregate(stored: StoredCharacter)
}
@Singleton
class JooqCharacterRepository
@Inject
constructor(
private val dsl: DSLContext,
@param:Named("db") private val dispatcher: CoroutineDispatcher,
) : CharacterRepository {
override suspend fun loadByUser(userId: Int): List<StoredCharacter> =
withContext(dispatcher) {
hydrate(dsl.selectFrom(CHARACTERS).where(CHARACTERS.USER_ID.eq(userId)).fetch())
}
override suspend fun loadById(id: Long): StoredCharacter? =
withContext(dispatcher) {
val row = dsl.selectFrom(CHARACTERS).where(CHARACTERS.ID.eq(id)).fetchOne()
row?.let { hydrate(listOf(it)).single() }
}
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) =
withContext(dispatcher) {
dsl.transaction { cfg ->
val tx = cfg.dsl()
tx.deleteFrom(CHARACTERS).where(CHARACTERS.ID.eq(stored.info.id)).execute()
insert(tx, stored)
}
}
private fun insert(tx: DSLContext, stored: StoredCharacter) {
tx.insertInto(CHARACTERS).set(stored.info.toRecord()).execute()
val monsters = stored.pokemon + stored.pcStorage
if (monsters.isNotEmpty()) {
tx.batchInsert(monsters.map { it.toRecord() }).execute()
}
for ((itemId, quantity) in stored.items) {
tx.insertInto(CHARACTER_ITEMS)
.set(CHARACTER_ITEMS.CHARACTER_ID, stored.info.id)
.set(CHARACTER_ITEMS.ITEM_ID, itemId)
.set(CHARACTER_ITEMS.QUANTITY, quantity)
.execute()
}
}
/** Loads pokemon and items for all rows in one query each instead of per character. */
private fun hydrate(rows: List<CharactersRecord>): List<StoredCharacter> {
if (rows.isEmpty()) return emptyList()
val ids = rows.map { it.id }
val monstersByOwner: Map<Long, List<Pokemon>> =
dsl.selectFrom(POKEMON)
.where(POKEMON.OWNER_ID.`in`(ids))
.orderBy(POKEMON.OWNER_ID, POKEMON.CONTAINER, POKEMON.CONTAINER_SLOT)
.fetch()
.map { it.toPokemon() }
.groupBy { it.ownerId }
val itemsByOwner: Map<Long, Map<Int, Int>> =
dsl.selectFrom(CHARACTER_ITEMS)
.where(CHARACTER_ITEMS.CHARACTER_ID.`in`(ids))
.fetch()
.groupBy({ it.characterId }, { it.itemId to it.quantity })
.mapValues { (_, pairs) -> pairs.toMap() }
return rows.map { row ->
val monsters = monstersByOwner[row.id].orEmpty()
val (party, pc) = monsters.partition { it.container == PokemonContainer.PARTY }
StoredCharacter(
info = row.toInfo(),
pokemon = party.toMutableList(),
pcStorage = pc.toMutableList(),
items = itemsByOwner[row.id].orEmpty().toMutableMap(),
)
}
}
private fun CharacterInfo.toRecord(): CharactersRecord =
CharactersRecord(
id = id,
userId = userId,
name = name,
namePrefix = namePrefix,
rivalSex = rivalSex.toShort(),
lastLogin = lastLogin,
createdAt = createdAt,
money = money,
permissions = permissions,
remainingSafariSteps = remainingSafariSteps,
remainingSafariBalls = remainingSafariBalls.toShort(),
pcExtraSlots = pcExtraSlots.toShort(),
battleBoxExtraSlots = battleBoxExtraSlots.toShort(),
templateAmount = templateAmount.toShort(),
positionRegionId = positionRegionId.toShort(),
positionBankId = positionBankId.toShort(),
positionMapId = positionMapId.toShort(),
positionX = positionX,
positionY = positionY,
repelLeft = repelLeft,
repelItemId = repelItemId,
lureLeft = lureLeft,
lureItemId = lureItemId,
)
private fun CharactersRecord.toInfo(): CharacterInfo =
CharacterInfo(
id = id,
name = name,
namePrefix = namePrefix ?: "",
userId = userId,
rivalSex = rivalSex.toByte(),
lastLogin = lastLogin,
createdAt = createdAt,
money = money,
permissions = permissions,
remainingSafariSteps = remainingSafariSteps,
remainingSafariBalls = remainingSafariBalls.toByte(),
pcExtraSlots = pcExtraSlots.toByte(),
battleBoxExtraSlots = battleBoxExtraSlots.toByte(),
templateAmount = templateAmount.toByte(),
positionRegionId = positionRegionId.toByte(),
positionBankId = positionBankId.toByte(),
positionMapId = positionMapId.toByte(),
positionX = positionX,
positionY = positionY,
repelLeft = repelLeft,
repelItemId = repelItemId,
lureLeft = lureLeft,
lureItemId = lureItemId,
)
private fun Pokemon.toRecord(): PokemonRecord =
PokemonRecord(
id = id,
ownerId = ownerId,
container = container.name,
containerSlot = containerSlot,
dexId = dexId,
seed = seed,
ot = ot,
nickname = nickname,
pokemonLevel = level.toShort(),
hp = hp,
xp = xp,
evHp = eVs.hp.toShort(),
evAtk = eVs.atk.toShort(),
evDef = eVs.def.toShort(),
evSpAtk = eVs.spAtk.toShort(),
evSpDef = eVs.spDef.toShort(),
evSpd = eVs.spd.toShort(),
ivHp = iVs.hp.toShort(),
ivAtk = iVs.atk.toShort(),
ivDef = iVs.def.toShort(),
ivSpAtk = iVs.spAtk.toShort(),
ivSpDef = iVs.spDef.toShort(),
ivSpd = iVs.spd.toShort(),
move1Id = moves.getOrNull(0)?.id ?: 0,
move1Pp = (moves.getOrNull(0)?.pp ?: 0).toShort(),
move2Id = moves.getOrNull(1)?.id ?: 0,
move2Pp = (moves.getOrNull(1)?.pp ?: 0).toShort(),
move3Id = moves.getOrNull(2)?.id ?: 0,
move3Pp = (moves.getOrNull(2)?.pp ?: 0).toShort(),
move4Id = moves.getOrNull(3)?.id ?: 0,
move4Pp = (moves.getOrNull(3)?.pp ?: 0).toShort(),
isShiny = isShiny,
hasHiddenAbility = hasHiddenAbility,
isAlpha = isAlpha,
isSecret = isSecret,
isFatefulEncounter = isFatefulEncounter,
isRaidEncounter = isRaidEncounter,
isEgg = isEgg,
caughtAt = caughtAt,
)
private fun PokemonRecord.toPokemon(): Pokemon =
Pokemon(
id = id,
ownerId = ownerId,
container = PokemonContainer.valueOf(container),
containerSlot = containerSlot,
dexId = dexId,
seed = seed,
ot = ot,
nickname = nickname ?: "",
level = pokemonLevel.toByte(),
hp = hp,
xp = xp,
eVs = hydrateEvs(),
iVs = hydrateIvs(),
moves =
listOf(
PokemonMove(move1Id ?: 0, (move1Pp ?: 0).toByte()),
PokemonMove(move2Id ?: 0, (move2Pp ?: 0).toByte()),
PokemonMove(move3Id ?: 0, (move3Pp ?: 0).toByte()),
PokemonMove(move4Id ?: 0, (move4Pp ?: 0).toByte()),
),
isShiny = isShiny ?: false,
hasHiddenAbility = hasHiddenAbility ?: false,
isAlpha = isAlpha ?: false,
isSecret = isSecret ?: false,
isFatefulEncounter = isFatefulEncounter ?: false,
isRaidEncounter = isRaidEncounter ?: false,
isEgg = isEgg ?: false,
caughtAt = caughtAt,
)
// The stat setters reject zero, so only set stats that are above it.
private fun PokemonStats.setPositive(
hp: Short?,
atk: Short?,
def: Short?,
spAtk: Short?,
spDef: Short?,
spd: Short?,
) {
hp?.toInt()?.let { if (it > 0) this.hp = it }
atk?.toInt()?.let { if (it > 0) this.atk = it }
def?.toInt()?.let { if (it > 0) this.def = it }
spAtk?.toInt()?.let { if (it > 0) this.spAtk = it }
spDef?.toInt()?.let { if (it > 0) this.spDef = it }
spd?.toInt()?.let { if (it > 0) this.spd = it }
}
private fun PokemonRecord.hydrateEvs(): EVs =
EVs().also { it.setPositive(evHp, evAtk, evDef, evSpAtk, evSpDef, evSpd) }
private fun PokemonRecord.hydrateIvs(): IVs =
IVs().also { it.setPositive(ivHp, ivAtk, ivDef, ivSpAtk, ivSpDef, ivSpd) }
}
@@ -6,22 +6,29 @@ import de.fiereu.openmmo.common.PokemonMove
import de.fiereu.openmmo.common.enums.EVs
import de.fiereu.openmmo.common.enums.IVs
import de.fiereu.openmmo.common.enums.PokemonContainer
import io.github.oshai.kotlinlogging.KotlinLogging
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
private val log = KotlinLogging.logger {}
// The starter party every new character gets.
const val SNIVY_DEX_ID = 495
const val PATRAT_DEX_ID = 504
// Low bits tag an entity id's kind, so character and monster ids never collide.
private const val CHARACTER_ID_TAG = 0x9000L
private const val MONSTER_ID_TAG = 0xC000L
// Dev accounts, one character each.
private val DEV_CHARACTER_NAMES = mapOf(1 to "Test", 2 to "Test2")
private val FLUSH_TICK = 5.seconds
private val FLUSH_DEBOUNCE = 10.seconds
data class StoredCharacter(
val info: CharacterInfo,
@@ -30,29 +37,36 @@ data class StoredCharacter(
val items: MutableMap<Int, Int>,
)
/**
* Write-through cache over [CharacterRepository]. Memory is the live version and the database
* mirrors it. Aggregates enter the database on creation and are written back when marked dirty:
* after a debounce by the periodic flusher, or immediately through [flushCharacterAsync] on events
* like warps. A disconnect goes through [unloadCharacterAsync], which also evicts the aggregate
* from the cache once its last write succeeded, so only connected players stay in memory.
*/
@Singleton
class CharacterStore @Inject constructor() {
class CharacterStore
@Inject
constructor(
private val repository: CharacterRepository,
private val entityIds: EntityIdService,
scope: CoroutineScope,
) {
private val flushJob = SupervisorJob()
private val flushScope = CoroutineScope(scope.coroutineContext + flushJob)
private var periodicJob: Job? = null
private val characters = ConcurrentHashMap<Long, StoredCharacter>()
private val charactersByUser = ConcurrentHashMap<Int, MutableList<Long>>()
private val nextEntityId = AtomicLong(1)
init {
ensureDevCharacters()
}
private fun ensureDevCharacters() {
if (characters.isNotEmpty()) return
for ((userId, name) in DEV_CHARACTER_NAMES) createCharacter(userId, name)
}
private fun generateEntityId(tag: Long): Long = (nextEntityId.getAndIncrement() shl 16) or tag
private val charactersByUser = ConcurrentHashMap<Int, CopyOnWriteArrayList<Long>>()
private val dirtySince = ConcurrentHashMap<Long, Long>()
private val pendingUnload = ConcurrentHashMap.newKeySet<Long>()
/** Create a character with its own entity id and a starter party with its own monster uids. */
fun createCharacter(
suspend fun createCharacter(
userId: Int,
name: String,
): StoredCharacter {
val id = generateEntityId(CHARACTER_ID_TAG)
val id = entityIds.newCharacterId()
val now = LocalDateTime.now()
val info =
CharacterInfo(
@@ -83,20 +97,40 @@ class CharacterStore @Inject constructor() {
val stored = StoredCharacter(info, mutableListOf(), mutableListOf(), mutableMapOf())
stored.pokemon.add(starterSnivy(id, name))
stored.pokemon.add(starterPatrat(id, name))
repository.insertAggregate(stored)
characters[id] = stored
charactersByUser.getOrPut(userId) { mutableListOf() }.add(id)
charactersByUser.computeIfAbsent(userId) { CopyOnWriteArrayList() }.add(id)
return stored
}
fun getCharacter(id: Long): StoredCharacter? = characters[id]
fun getCharactersByUser(userId: Int): List<StoredCharacter> {
return charactersByUser[userId]?.mapNotNull { characters[it] } ?: emptyList()
/** Like [getCharacter] but falls back to the database when the cache has no entry. */
suspend fun getOrLoadCharacter(id: Long): StoredCharacter? {
pendingUnload.remove(id)
characters[id]?.let {
return it
}
val loaded = repository.loadById(id) ?: return null
return cache(loaded)
}
suspend fun getCharactersByUser(userId: Int): List<StoredCharacter> {
val cachedIds: List<Long>? = charactersByUser[userId]
if (cachedIds != null) {
cachedIds.forEach { pendingUnload.remove(it) }
return cachedIds.mapNotNull { characters[it] }
}
val loaded = repository.loadByUser(userId).map { cache(it) }
loaded.forEach { pendingUnload.remove(it.info.id) }
charactersByUser.putIfAbsent(userId, CopyOnWriteArrayList(loaded.map { it.info.id }))
return loaded
}
fun updateCharacter(info: CharacterInfo) {
val stored = characters[info.id] ?: return
characters[info.id] = stored.copy(info = info)
markDirty(info.id)
}
fun updatePosition(
@@ -116,11 +150,103 @@ class CharacterStore @Inject constructor() {
positionMapId = mapId ?: oldInfo.positionMapId,
)
characters[characterId] = stored.copy(info = newInfo)
markDirty(characterId)
}
fun addPokemon(characterId: Long, pokemon: Pokemon) {
val stored = characters[characterId] ?: return
// Copy instead of mutating in place, so flusher snapshots never see a half-updated list.
characters[characterId] = stored.copy(pokemon = (stored.pokemon + pokemon).toMutableList())
markDirty(characterId)
}
fun addMoney(characterId: Long, amount: Int) {
val stored = characters[characterId] ?: return
val newInfo = stored.info.copy(money = stored.info.money + amount)
characters[characterId] = stored.copy(info = newInfo)
markDirty(characterId)
}
fun startPeriodicFlush() {
periodicJob =
flushScope.launch {
while (isActive) {
delay(FLUSH_TICK)
flushOlderThan(FLUSH_DEBOUNCE.inWholeMilliseconds)
}
}
}
/** Flush one character soon, skipping the debounce. Safe to call from Netty threads. */
fun flushCharacterAsync(characterId: Long) {
flushScope.launch { flush(characterId) }
}
/**
* Persist the character and drop it from the cache once the write succeeded. While the save keeps
* failing the character stays cached and dirty, and the periodic flusher finishes the eviction on
* its next successful write. Loading the character again cancels the unload.
*/
fun unloadCharacterAsync(characterId: Long) {
pendingUnload.add(characterId)
flushScope.launch { flush(characterId) }
}
suspend fun flushAll() {
for (id in dirtySince.keys) flush(id)
}
/** Stop the periodic loop, wait for in-flight flushes, then persist whatever is still dirty. */
suspend fun shutdown() {
periodicJob?.cancel()
flushJob.children.toList().joinAll()
flushAll()
}
private fun cache(stored: StoredCharacter): StoredCharacter {
val existing = characters.putIfAbsent(stored.info.id, stored)
return existing ?: stored
}
private fun markDirty(id: Long) {
dirtySince.putIfAbsent(id, System.currentTimeMillis())
}
private suspend fun flushOlderThan(ageMs: Long) {
val now = System.currentTimeMillis()
for ((id, since) in dirtySince) {
if (now - since >= ageMs) flush(id)
}
}
private suspend fun flush(id: Long) {
val since = dirtySince.remove(id)
val stored = characters[id]
if (since != null && stored != null) {
try {
repository.saveAggregate(stored)
} catch (e: Exception) {
log.warn(e) { "Failed to persist character $id, will retry" }
dirtySince.putIfAbsent(id, since)
return
}
}
maybeEvict(id)
}
private fun maybeEvict(id: Long) {
if (!pendingUnload.remove(id)) return
if (dirtySince.containsKey(id)) {
pendingUnload.add(id)
return
}
val stored = characters.remove(id) ?: return
charactersByUser.remove(stored.info.userId)
}
private fun starterSnivy(ownerId: Long, ot: String): Pokemon =
Pokemon(
id = generateEntityId(MONSTER_ID_TAG),
id = entityIds.newMonsterId(),
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 0,
@@ -151,7 +277,7 @@ class CharacterStore @Inject constructor() {
private fun starterPatrat(ownerId: Long, ot: String): Pokemon =
Pokemon(
id = generateEntityId(MONSTER_ID_TAG),
id = entityIds.newMonsterId(),
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 1,
@@ -179,14 +305,4 @@ class CharacterStore @Inject constructor() {
isRaidEncounter = false,
caughtAt = LocalDateTime.now(),
)
fun addPokemon(characterId: Long, pokemon: Pokemon) {
characters[characterId]?.pokemon?.add(pokemon)
}
fun addMoney(characterId: Long, amount: Int) {
val stored = characters[characterId] ?: return
val newInfo = stored.info.copy(money = stored.info.money + amount)
characters[characterId] = stored.copy(info = newInfo)
}
}
@@ -0,0 +1,33 @@
package de.fiereu.openmmo.server.game.storage
import java.util.concurrent.ThreadLocalRandom
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject
import javax.inject.Singleton
const val CHARACTER_ID_TAG = 0x9000L
const val MONSTER_ID_TAG = 0xC000L
/**
* Creates entity ids without a database roundtrip, safe to call from any thread.
*
* An id is a 47-bit head shifted left 16 with the kind tag in the low bits. The head combines 39
* bits of unix millis with an 8-bit counter that starts at a random offset, so ids are unique
* within a process as long as fewer than 256 are created in the same millisecond. The sign bit
* stays clear. The wire protocol depends on the low-16 tag, so keep it intact.
*/
@Singleton
class EntityIdService @Inject constructor() {
private val counter = AtomicLong(ThreadLocalRandom.current().nextLong(256))
fun newCharacterId(): Long = newId(CHARACTER_ID_TAG)
fun newMonsterId(): Long = newId(MONSTER_ID_TAG)
private fun newId(tag: Long): Long {
val millis = System.currentTimeMillis() and 0x7F_FFFF_FFFFL
val head = (millis shl 8) or (counter.getAndIncrement() and 0xFF)
return (head shl 16) or tag
}
}
@@ -6,3 +6,21 @@ server {
sessionSecret = "dev-only-secret-do-not-use-in-production"
sessionSecret = ${?OPENMMO_SESSION_SECRET}
}
db {
host = "localhost"
host = ${?GAME_DB_HOST}
port = 20021
port = ${?GAME_DB_PORT}
name = "openmmo_game_db"
name = ${?GAME_DB_NAME}
user = "openmmo_game_user"
user = ${?GAME_DB_USER}
password = "changeMe!"
password = ${?GAME_DB_PASSWORD}
poolSize = 4
poolSize = ${?GAME_DB_POOL_SIZE}
# Applies the dev seed data in db/dev. Turn off in production.
seedDev = true
seedDev = ${?GAME_DB_SEED_DEV}
}
@@ -0,0 +1,27 @@
-- One character per dev account, each with the Snivy and Patrat starter party.
-- Only applied when db.seedDev is enabled, never in production.
-- Ids are fixed low values with the kind tag in the low 16 bits. Runtime ids from
-- EntityIdService carry a timestamp head, so they can never collide with these.
INSERT INTO characters (
id, user_id, name, name_prefix, rival_sex, last_login, created_at, money, permissions,
remaining_safari_steps, remaining_safari_balls, pc_extra_slots, battle_box_extra_slots,
template_amount, position_region_id, position_bank_id, position_map_id, position_x,
position_y, repel_left, repel_item_id, lure_left, lure_item_id
)
VALUES
(102400, 1, 'Test', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 30000, 8,
0, 0, 0, 0, 0, 1, 51, 3, 4, 4, 0, 0, 0, 0),
(364544, 2, 'Test2', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 30000, 8,
0, 0, 0, 0, 0, 1, 51, 3, 4, 4, 0, 0, 0, 0)
ON CONFLICT (id) DO NOTHING;
INSERT INTO pokemon (
id, owner_id, container, container_slot, dex_id, seed, ot, pokemon_level, hp, xp,
move1_id, move1_pp, move2_id, move2_pp, caught_at
)
VALUES
(180224, 102400, 'PARTY', 0, 495, 0, 'Test', 5, 20, 165, 33, 35, 43, 30, CURRENT_TIMESTAMP),
(311296, 102400, 'PARTY', 1, 504, 0, 'Test', 3, 12, 27, 33, 35, 0, 0, CURRENT_TIMESTAMP),
(442368, 364544, 'PARTY', 0, 495, 0, 'Test2', 5, 20, 165, 33, 35, 43, 30, CURRENT_TIMESTAMP),
(507904, 364544, 'PARTY', 1, 504, 0, 'Test2', 3, 12, 27, 33, 35, 0, 0, CURRENT_TIMESTAMP)
ON CONFLICT (id) DO NOTHING;
@@ -0,0 +1,86 @@
-- Entity ids come from EntityIdService. The low 16 bits tag the kind
-- (0x9000 characters, 0xC000 monsters) and the wire protocol depends on that tag.
CREATE TABLE characters (
id BIGINT NOT NULL PRIMARY KEY,
-- Account id from the login database. That is another database, so no FK.
user_id INT NOT NULL,
name VARCHAR(32) NOT NULL,
name_prefix VARCHAR(32) NOT NULL DEFAULT '',
rival_sex SMALLINT NOT NULL,
last_login TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL,
money INT NOT NULL,
permissions INT NOT NULL,
remaining_safari_steps SMALLINT NOT NULL,
remaining_safari_balls SMALLINT NOT NULL,
pc_extra_slots SMALLINT NOT NULL,
battle_box_extra_slots SMALLINT NOT NULL,
template_amount SMALLINT NOT NULL,
position_region_id SMALLINT NOT NULL,
position_bank_id SMALLINT NOT NULL,
position_map_id SMALLINT NOT NULL,
position_x SMALLINT NOT NULL,
position_y SMALLINT NOT NULL,
repel_left SMALLINT NOT NULL,
repel_item_id SMALLINT NOT NULL,
lure_left SMALLINT NOT NULL,
lure_item_id SMALLINT NOT NULL
);
CREATE INDEX idx_characters_user_id ON characters (user_id);
CREATE INDEX idx_characters_name ON characters (name);
CREATE TABLE pokemon (
id BIGINT NOT NULL PRIMARY KEY,
owner_id BIGINT NOT NULL REFERENCES characters (id) ON DELETE CASCADE,
-- PokemonContainer enum name. Renaming an enum entry breaks stored data.
container VARCHAR(16) NOT NULL,
container_slot SMALLINT NOT NULL,
dex_id INT NOT NULL,
-- Nature is derived from the seed and not stored separately.
seed INT NOT NULL,
ot VARCHAR(32) NOT NULL,
nickname VARCHAR(32) NOT NULL DEFAULT '',
pokemon_level SMALLINT NOT NULL,
hp SMALLINT NOT NULL,
xp INT NOT NULL,
ev_hp SMALLINT NOT NULL DEFAULT 0,
ev_atk SMALLINT NOT NULL DEFAULT 0,
ev_def SMALLINT NOT NULL DEFAULT 0,
ev_sp_atk SMALLINT NOT NULL DEFAULT 0,
ev_sp_def SMALLINT NOT NULL DEFAULT 0,
ev_spd SMALLINT NOT NULL DEFAULT 0,
iv_hp SMALLINT NOT NULL DEFAULT 0,
iv_atk SMALLINT NOT NULL DEFAULT 0,
iv_def SMALLINT NOT NULL DEFAULT 0,
iv_sp_atk SMALLINT NOT NULL DEFAULT 0,
iv_sp_def SMALLINT NOT NULL DEFAULT 0,
iv_spd SMALLINT NOT NULL DEFAULT 0,
move1_id SMALLINT NOT NULL DEFAULT 0,
move1_pp SMALLINT NOT NULL DEFAULT 0,
move2_id SMALLINT NOT NULL DEFAULT 0,
move2_pp SMALLINT NOT NULL DEFAULT 0,
move3_id SMALLINT NOT NULL DEFAULT 0,
move3_pp SMALLINT NOT NULL DEFAULT 0,
move4_id SMALLINT NOT NULL DEFAULT 0,
move4_pp SMALLINT NOT NULL DEFAULT 0,
is_shiny BOOLEAN NOT NULL DEFAULT FALSE,
has_hidden_ability BOOLEAN NOT NULL DEFAULT FALSE,
is_alpha BOOLEAN NOT NULL DEFAULT FALSE,
is_secret BOOLEAN NOT NULL DEFAULT FALSE,
is_fateful_encounter BOOLEAN NOT NULL DEFAULT FALSE,
is_raid_encounter BOOLEAN NOT NULL DEFAULT FALSE,
is_egg BOOLEAN NOT NULL DEFAULT FALSE,
caught_at TIMESTAMP NOT NULL
);
CREATE INDEX idx_pokemon_owner ON pokemon (owner_id);
CREATE UNIQUE INDEX uq_pokemon_owner_container_slot ON pokemon (owner_id, container, container_slot);
CREATE TABLE character_items (
character_id BIGINT NOT NULL REFERENCES characters (id) ON DELETE CASCADE,
item_id INT NOT NULL,
quantity INT NOT NULL,
PRIMARY KEY (character_id, item_id)
);
@@ -6,25 +6,35 @@ import de.fiereu.openmmo.net.game.packets.EntityLeavePacket
import de.fiereu.openmmo.net.game.packets.EntityMovePacket
import de.fiereu.openmmo.net.game.packets.LoadEntityPacket
import de.fiereu.openmmo.server.game.storage.CharacterStore
import de.fiereu.openmmo.server.game.storage.EntityIdService
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import de.fiereu.openmmo.server.game.testsupport.FakeSession
import de.fiereu.openmmo.server.game.world.interest.InterestManager
import de.fiereu.openmmo.server.game.world.interest.PassThroughInterestPolicy
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
class PresenceServiceTest :
FunSpec({
val mapManager = MapManager()
fun freshPresence(): Pair<PresenceService, CharacterStore> {
val store = CharacterStore()
val store =
CharacterStore(
FakeCharacterRepository(),
EntityIdService(),
CoroutineScope(SupervisorJob() + Dispatchers.Unconfined),
)
val presence =
PresenceService(
InterestManager(), PassThroughInterestPolicy(), MapLoadService(mapManager), store)
return presence to store
}
fun CharacterStore.session(name: String, mapId: Int = 3): FakeSession {
suspend fun CharacterStore.session(name: String, mapId: Int = 3): FakeSession {
val character = createCharacter(userId = 1, name = name)
return FakeSession(characterId = character.info.id, mapId = mapId)
}
@@ -0,0 +1,177 @@
package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.PokemonMove
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.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.nulls.shouldBeNull
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import kotlinx.coroutines.Dispatchers
import org.flywaydb.core.Flyway
import org.jooq.impl.DSL
import org.testcontainers.containers.PostgreSQLContainer
@EnabledIf(DockerAvailable::class)
class CharacterRepositoryIT :
FunSpec({
val container = PostgreSQLContainer<Nothing>("postgres:18")
val entityIds = EntityIdService()
lateinit var repository: JooqCharacterRepository
// Postgres timestamps have microsecond precision, so nanos would not round-trip.
fun now(): LocalDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.MICROS)
fun monster(ownerId: Long, container: PokemonContainer, slot: Short): Pokemon =
Pokemon(
id = entityIds.newMonsterId(),
ownerId = ownerId,
container = container,
containerSlot = slot,
dexId = 495,
seed = 12345,
ot = "Ash",
nickname = "Smugleaf",
level = 5,
hp = 20,
xp = 165,
eVs = EVs().also { it.hp = 4 },
iVs = IVs().also { it.atk = 31 },
moves =
listOf(
PokemonMove(33, 35),
PokemonMove(43, 30),
PokemonMove(0, 0),
PokemonMove(0, 0),
),
isShiny = true,
hasHiddenAbility = false,
isAlpha = false,
isSecret = false,
isFatefulEncounter = true,
isRaidEncounter = false,
caughtAt = now(),
)
// Each test uses its own userId. User 1 belongs to the seeded dev character.
fun aggregate(userId: Int): StoredCharacter {
val id = entityIds.newCharacterId()
val info =
CharacterInfo(
id = id,
name = "Ash",
namePrefix = "",
userId = userId,
rivalSex = 1,
lastLogin = now(),
createdAt = now(),
money = 30000,
permissions = 8,
remainingSafariSteps = 12,
remainingSafariBalls = 3,
pcExtraSlots = 0,
battleBoxExtraSlots = 0,
templateAmount = 0,
positionRegionId = 1,
positionBankId = 51,
positionMapId = 3,
positionX = 4,
positionY = 4,
repelLeft = 0,
repelItemId = 0,
lureLeft = 0,
lureItemId = 0,
)
return StoredCharacter(
info = info,
pokemon = mutableListOf(monster(id, PokemonContainer.PARTY, 0)),
pcStorage = mutableListOf(monster(id, PokemonContainer.PC, 0)),
items = mutableMapOf(4 to 10),
)
}
// An all-zero stats monster, like the seeded starters. Hydration must not choke on it.
fun zeroStatsMonster(ownerId: Long): Pokemon =
monster(ownerId, PokemonContainer.PARTY, 1)
.copy(eVs = EVs(), iVs = IVs(), isShiny = false, isFatefulEncounter = false)
beforeSpec {
container.start()
Flyway.configure()
.dataSource(container.jdbcUrl, container.username, container.password)
.locations("classpath:db/migration", "classpath:db/dev")
.load()
.migrate()
val dsl = DSL.using(container.jdbcUrl, container.username, container.password)
repository = JooqCharacterRepository(dsl, Dispatchers.IO)
}
afterSpec { container.stop() }
test("insert and load round-trips the whole aggregate") {
val stored = aggregate(userId = 60)
stored.pokemon.add(zeroStatsMonster(stored.info.id))
repository.insertAggregate(stored)
val loaded = repository.loadById(stored.info.id).shouldNotBeNull()
loaded.info shouldBe stored.info
loaded.pokemon shouldBe stored.pokemon
loaded.pcStorage shouldBe stored.pcStorage
loaded.items shouldBe stored.items
(loaded.info.id and 0xFFFF) shouldBe CHARACTER_ID_TAG
}
test("loadByUser returns only that user's characters") {
val mine = aggregate(userId = 77)
val other = aggregate(userId = 78)
repository.insertAggregate(mine)
repository.insertAggregate(other)
repository.loadByUser(77).map { it.info.id } shouldBe listOf(mine.info.id)
}
test("saveAggregate replaces the character, pokemon, and items") {
val stored = aggregate(userId = 90)
repository.insertAggregate(stored)
val mutated =
stored.copy(
info = stored.info.copy(money = 999, positionX = 12),
pokemon = mutableListOf(monster(stored.info.id, PokemonContainer.PARTY, 0)),
pcStorage = mutableListOf(),
items = mutableMapOf(4 to 9, 13 to 1),
)
repository.saveAggregate(mutated)
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.items shouldBe mapOf(4 to 9, 13 to 1)
}
test("loadById returns null for an unknown id") {
repository.loadById(entityIds.newCharacterId()).shouldBeNull()
}
test("a duplicate container slot is rejected") {
val stored = aggregate(userId = 92)
stored.pokemon.add(monster(stored.info.id, PokemonContainer.PARTY, 0))
shouldThrowAny { repository.insertAggregate(stored) }
}
test("the seed migration provides the dev characters with their starters") {
val seeded = repository.loadByUser(1)
seeded.map { it.info.name } shouldBe listOf("Test")
seeded.single().pokemon.map { it.dexId } shouldBe listOf(495, 504)
}
})
@@ -0,0 +1,156 @@
package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.server.game.testsupport.FakeCharacterRepository
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
class CharacterStoreCacheTest :
FunSpec({
test("createCharacter inserts the aggregate into the repository") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val created = store.createCharacter(1, "Ash")
repo.saved[created.info.id].shouldNotBeNull()
repo.saved[created.info.id]!!.pokemon.size shouldBe 2
}
}
test("mutations flush through flushAll") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash").info.id
store.updatePosition(id, 10, 20)
store.flushAll()
repo.saved[id]!!.info.positionX shouldBe 10.toShort()
repo.saved[id]!!.info.positionY shouldBe 20.toShort()
}
}
test("reads come from memory, not the repository") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash").info.id
store.addMoney(id, 5000)
store.getCharacter(id)!!.info.money shouldBe 35000
repo.saved[id]!!.info.money shouldBe 30000
}
}
test("addPokemon copies instead of mutating the cached list") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val created = store.createCharacter(1, "Ash")
val before = store.getCharacter(created.info.id)!!.pokemon
val extra = before.first().copy(id = EntityIdService().newMonsterId(), containerSlot = 2)
store.addPokemon(created.info.id, extra)
before.size shouldBe 2
store.getCharacter(created.info.id)!!.pokemon.size shouldBe 3
}
}
test("a failed flush keeps the character dirty and retries") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash").info.id
store.addMoney(id, 1)
repo.failNextSave = true
store.flushAll()
repo.saveCount.get() shouldBe 0
store.flushAll()
repo.saveCount.get() shouldBe 1
repo.saved[id]!!.info.money shouldBe 30001
}
}
test("unload persists and evicts after the flush succeeds") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), this)
val id = store.createCharacter(1, "Ash").info.id
store.addMoney(id, 5)
store.unloadCharacterAsync(id)
advanceUntilIdle()
store.getCharacter(id) shouldBe null
repo.saved[id]!!.info.money shouldBe 30005
store.getCharactersByUser(1).map { it.info.id } shouldBe listOf(id)
}
}
test("unload keeps the character cached until a save succeeds") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), this)
val id = store.createCharacter(1, "Ash").info.id
store.addMoney(id, 1)
repo.failNextSave = true
store.unloadCharacterAsync(id)
advanceUntilIdle()
store.getCharacter(id).shouldNotBeNull()
store.flushAll()
store.getCharacter(id) shouldBe null
repo.saved[id]!!.info.money shouldBe 30001
}
}
test("loading a character again cancels a pending unload") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), this)
val id = store.createCharacter(1, "Ash").info.id
store.unloadCharacterAsync(id)
store.getOrLoadCharacter(id).shouldNotBeNull()
advanceUntilIdle()
store.getCharacter(id).shouldNotBeNull()
}
}
test("shutdown flushes what is still dirty") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), this)
val id = store.createCharacter(1, "Ash").info.id
store.addMoney(id, 7)
store.shutdown()
repo.saved[id]!!.info.money shouldBe 30007
}
}
test("getCharactersByUser loads from the repository once") {
runTest {
val repo = FakeCharacterRepository()
val seedStore = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = seedStore.createCharacter(7, "Misty").info.id
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val loaded = store.getCharactersByUser(7)
loaded.map { it.info.id } shouldBe listOf(id)
store.getCharacter(id).shouldNotBeNull()
}
}
})
@@ -0,0 +1,26 @@
package de.fiereu.openmmo.server.game.storage
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
class EntityIdServiceTest :
FunSpec({
val service = EntityIdService()
test("character ids carry the character tag") {
val id = service.newCharacterId()
(id and 0xFFFF) shouldBe CHARACTER_ID_TAG
}
test("monster ids carry the monster tag") {
val id = service.newMonsterId()
(id and 0xFFFF) shouldBe MONSTER_ID_TAG
}
test("ids are positive") { repeat(100) { (service.newCharacterId() > 0) shouldBe true } }
test("a burst of ids has no duplicates") {
val ids = (1..200).map { service.newMonsterId() }
ids.toSet().size shouldBe ids.size
}
})
@@ -51,7 +51,7 @@ class GuildStoreTest :
byId.getValue(100L).leader shouldBe false
}
test("leave unbinds the leaver; disband removes the guild") {
test("leave unbinds the leaver and disband removes the guild") {
val store = GuildStore()
store.createGuild("Knights", "KNT", leaderId = 100L, leaderName = "Leader")
store.leaveGuild(100L)
@@ -0,0 +1,12 @@
package de.fiereu.openmmo.server.game.testsupport
import io.kotest.core.annotation.Condition
import io.kotest.core.spec.Spec
import kotlin.reflect.KClass
import org.testcontainers.DockerClientFactory
/** Gates Testcontainers specs so machines without Docker skip them instead of failing. */
class DockerAvailable : Condition {
override fun evaluate(kclass: KClass<out Spec>): Boolean =
runCatching { DockerClientFactory.instance().isDockerAvailable() }.getOrDefault(false)
}
@@ -0,0 +1,30 @@
package de.fiereu.openmmo.server.game.testsupport
import de.fiereu.openmmo.server.game.storage.CharacterRepository
import de.fiereu.openmmo.server.game.storage.StoredCharacter
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
class FakeCharacterRepository : CharacterRepository {
val saved = ConcurrentHashMap<Long, StoredCharacter>()
val saveCount = AtomicInteger(0)
var failNextSave = false
override suspend fun loadByUser(userId: Int): List<StoredCharacter> =
saved.values.filter { it.info.userId == userId }
override suspend fun loadById(id: Long): StoredCharacter? = saved[id]
override suspend fun insertAggregate(stored: StoredCharacter) {
saved[stored.info.id] = stored
}
override suspend fun saveAggregate(stored: StoredCharacter) {
if (failNextSave) {
failNextSave = false
throw IllegalStateException("simulated save failure")
}
saveCount.incrementAndGet()
saved[stored.info.id] = stored
}
}