fix(game): persist items, money and caught monsters before returning (#139)

* fix(game): persist items, money and caught monsters before returning

* fix(game): serialise flushes so a durable write cannot return early

* fix(game): queue battle and guild replies so they cannot cut into a suspended handler

* fix(game): refuse an economic change the database would not accept
This commit is contained in:
Fiereu authored and GitHub committed 2026-08-09 12:19:26 +02:00
1 parent 225371fccb
commit d69a0806ab
16 files changed
+372 -74

No files matched your search

@@ -122,21 +122,25 @@ constructor(
on<RequestSocialProfilePacket> { event -> socialService.onRequestSocialProfile(event) }
on<CancelSocialInteractionPacket> { event -> socialService.onCancelSocialInteraction(event) }
on<GuildCreatePacket> { event -> guildService.onCreateGuild(event) }
on<GuildInvitePacket> { event -> guildService.onGuildInvite(event) }
on<GuildRankPermissionUpdatePacket> { event -> guildService.onRankPermissionUpdate(event) }
on<GuildMemberRankAssignPacket> { event -> guildService.onRankAssign(event) }
on<GuildMemberKickPacket> { event -> guildService.onKick(event) }
on<GuildLeavePacket> { event -> guildService.onLeave(event) }
on<GuildDisbandPacket> { event -> guildService.onDisband(event) }
on<GuildMotdUpdatePacket> { event -> guildService.onMotdUpdate(event) }
on<GuildRankLabelUpdatePacket> { event -> guildService.onRankLabelUpdate(event) }
on<GuildActivityLogPageRequestPacket> { event -> guildService.onActivityLogPageRequest(event) }
onSuspend<GuildCreatePacket> { event -> guildService.onCreateGuild(event) }
onSuspend<GuildInvitePacket> { event -> guildService.onGuildInvite(event) }
onSuspend<GuildRankPermissionUpdatePacket> { event ->
guildService.onRankPermissionUpdate(event)
}
onSuspend<GuildMemberRankAssignPacket> { event -> guildService.onRankAssign(event) }
onSuspend<GuildMemberKickPacket> { event -> guildService.onKick(event) }
onSuspend<GuildLeavePacket> { event -> guildService.onLeave(event) }
onSuspend<GuildDisbandPacket> { event -> guildService.onDisband(event) }
onSuspend<GuildMotdUpdatePacket> { event -> guildService.onMotdUpdate(event) }
onSuspend<GuildRankLabelUpdatePacket> { event -> guildService.onRankLabelUpdate(event) }
onSuspend<GuildActivityLogPageRequestPacket> { event ->
guildService.onActivityLogPageRequest(event)
}
on<MoveLearnReplyPacket> { event -> battleService.onMoveLearnReply(event) }
onSuspend<MoveLearnReplyPacket> { event -> battleService.onMoveLearnReply(event) }
on<BattlePartySwitchPacket> { event -> battleService.onBattlePacket(event) }
on<BattleActionPacket> { event -> battleService.onBattlePacket(event) }
on<BattleActionSelectPacket> { event -> battleService.onBattleAction(event) }
onSuspend<BattleActionSelectPacket> { event -> battleService.onBattleAction(event) }
on<BattleLeavePacket> { event -> battleService.onBattlePacket(event) }
on<BattleSequencePacket> { event -> battleService.onBattlePacket(event) }
on<BattleSlotActionPacket> { event -> battleService.onBattlePacket(event) }
@@ -154,15 +158,15 @@ constructor(
on<BattleTransitionReadyPacket> { event -> battleService.onBattlePacket(event) }
on<BattleTeamPreviewConfirmPacket> { event -> battleService.onBattlePacket(event) }
on<BattleRewardSelectPacket> { event -> battleService.onBattlePacket(event) }
on<MapLoadedAckPacket> { event -> battleService.onClientReady(event) }
onSuspend<MapLoadedAckPacket> { event -> battleService.onClientReady(event) }
// The client sends an empty heartbeat packet.
on<NullPacket> {}
on<KeepAlivePacket> { event -> event.session.send(event.packet) }
on<ChatMessagePacket> { event -> onChatMessage(event) }
onSuspend<ChatMessagePacket> { event -> onChatMessage(event) }
// What the client sends when the player types. The text rides in target unless the mode
// carries a message of its own.
on<ChatMessageSendPacket> { event ->
onSuspend<ChatMessageSendPacket> { event ->
chatCommandService.tryHandle(event.session, event.packet.message ?: event.packet.target)
}
}
@@ -190,7 +194,7 @@ constructor(
)
}
private fun onChatMessage(event: PacketEvent<ChatMessagePacket>) {
private suspend fun onChatMessage(event: PacketEvent<ChatMessagePacket>) {
val state = event.session.attributes[PLAYER_STATE]
if (state == null) {
log.warn { "Chat message from session without PlayerState" }
@@ -129,13 +129,13 @@ internal constructor(
characterId?.let { story.setVar(it, key, value) }
}
fun givePokemon(dexId: Int, level: Int, vararg moveIds: Int) =
suspend fun givePokemon(dexId: Int, level: Int, vararg moveIds: Int) =
checkNotNull(player) { STORY_PLAYER_UNAVAILABLE }
.givePokemon(session, state, dexId, level, moveIds.toList())
fun healParty() = checkNotNull(player) { STORY_PLAYER_UNAVAILABLE }.healParty(session, state)
fun giveItem(itemId: Int, quantity: Int = 1): Boolean =
suspend fun giveItem(itemId: Int, quantity: Int = 1): Boolean =
checkNotNull(player) { STORY_PLAYER_UNAVAILABLE }.giveItem(session, state, itemId, quantity)
/** Take an item back out of the bag, the decomp removeitem. False when the bag lacks it. */
@@ -83,7 +83,7 @@ constructor(
log.info { "Battle packet ${event.packet::class.simpleName} received: ${event.packet}" }
}
fun onBattleAction(event: PacketEvent<BattleActionSelectPacket>) {
suspend fun onBattleAction(event: PacketEvent<BattleActionSelectPacket>) {
val charId = event.session.attributes[PLAYER_STATE]?.characterId ?: return
val battle = battles.byChar(charId) ?: return
if (battle.pendingResult != null) return
@@ -132,7 +132,7 @@ constructor(
}
/** Throws a ball at the monster. False when the character is not in a battle. */
fun catchActiveWild(charId: Long): Boolean {
suspend fun catchActiveWild(charId: Long): Boolean {
val battle = battles.byChar(charId) ?: return false
catchWild(battle)
return true
@@ -308,13 +308,13 @@ constructor(
return battle
}
private fun resolveTurn(battle: BattleInstance, moveId: Short) {
private suspend fun resolveTurn(battle: BattleInstance, moveId: Short) {
val events = engine.resolveTurn(battle, moveId)
emitter.sendEvents(battle, events)
afterTurn(battle)
}
private fun afterTurn(battle: BattleInstance) {
private suspend fun afterTurn(battle: BattleInstance) {
when {
battle.opponent.all { it.fainted } -> endVictory(battle)
battle.party.all { it.fainted } -> endDefeat(battle)
@@ -335,7 +335,7 @@ constructor(
}
}
private fun switchMon(battle: BattleInstance, partyIndex: Short) {
private suspend fun switchMon(battle: BattleInstance, partyIndex: Short) {
val target = partyIndex.toInt()
val mon = battle.party.getOrNull(target)
val forced = battle.activeMon().fainted
@@ -395,7 +395,7 @@ constructor(
battle.pendingResult = BattleResult.FLED
}
private fun catchWild(battle: BattleInstance) {
private suspend fun catchWild(battle: BattleInstance) {
if (!battle.catchable) {
emitter.sendNotice(battle, "You can't catch this monster.")
emitter.sendPrompt(battle)
@@ -430,18 +430,20 @@ constructor(
detail = BattleListEventDetail(listType = 1, value = 1),
),
)
characterStore.addPokemon(battle.charId, caught)
if (!characterStore.addPokemon(battle.charId, caught)) {
log.error { "Could not persist the monster char=${battle.charId} just caught" }
}
endBattle(battle, BattleResult.CAUGHT)
}
private fun endVictory(battle: BattleInstance) {
private suspend fun endVictory(battle: BattleInstance) {
awardXp(battle, battle.opponentMon())
val prize = battle.trainer?.let { rewards.trainerPrize(it, battle.opponent.last().level) } ?: 0
if (prize > 0) {
characterStore.addMoney(battle.charId, prize)
log.info { "char=${battle.charId} won $prize from ${battle.trainer?.name}" }
val paid = prize > 0 && characterStore.addMoney(battle.charId, prize)
if (prize > 0 && !paid) {
log.error { "Could not pay char=${battle.charId} the $prize prize" }
}
endBattle(battle, BattleResult.VICTORY, battle.activeMon().entityId, prize)
endBattle(battle, BattleResult.VICTORY, battle.activeMon().entityId, if (paid) prize else 0)
}
/**
@@ -43,7 +43,7 @@ constructor(
private val characterStore: CharacterStore,
) {
fun onCreateGuild(event: PacketEvent<GuildCreatePacket>) {
suspend fun onCreateGuild(event: PacketEvent<GuildCreatePacket>) {
val ctx = event.session
val state = ctx.attributes[PLAYER_STATE] ?: return
val charId = state.characterId ?: return
@@ -32,7 +32,7 @@ constructor(
) {
/** Gives a story Pokemon and syncs it. */
fun givePokemon(
suspend fun givePokemon(
session: SessionContext,
state: PlayerState,
dexId: Int,
@@ -51,7 +51,8 @@ constructor(
ot = stored.info.name,
moves = paddedMoves(moveIds),
)
characters.addPokemon(characterId, pokemon)
// Only tell the client about it once the database has it.
if (!characters.addPokemon(characterId, pokemon)) return null
// Send the granted Pokemon's full record.
session.send(SocialListEntryAddPacket(pokemon))
species.get(dexId)?.let { session.send(acquiredMonsterDelta(pokemon, it)) }
@@ -90,7 +91,12 @@ constructor(
))
}
fun giveItem(session: SessionContext, state: PlayerState, itemId: Int, quantity: Int): Boolean {
suspend fun giveItem(
session: SessionContext,
state: PlayerState,
itemId: Int,
quantity: Int
): Boolean {
val characterId = state.characterId ?: return false
if (!characters.addItem(characterId, itemId, quantity)) return false
val items = characters.getCharacter(characterId)?.items ?: return false
@@ -12,7 +12,7 @@ class CatchCommand @Inject constructor(private val battleService: BattleService)
override val description = "throws a ball at the monster you are fighting"
override val permission = CharacterPermissions.DEVELOPER
override fun run(ctx: CommandContext) {
override suspend fun run(ctx: CommandContext) {
if (!battleService.catchActiveWild(ctx.characterId)) {
ctx.reply("You are not in a battle.")
}
@@ -16,7 +16,7 @@ interface ChatCommand {
// Runs on the thread the packet arrived on. Anything that waits for the client needs its own
// scope first.
fun run(ctx: CommandContext)
suspend fun run(ctx: CommandContext)
}
class CommandContext(
@@ -24,7 +24,7 @@ constructor(
private val commands = registered.associateBy { it.name.lowercase() }
/** Handles a chat line. Returns false when it is ordinary chat the caller should broadcast. */
fun tryHandle(session: SessionContext, message: String): Boolean {
suspend fun tryHandle(session: SessionContext, message: String): Boolean {
val text = message.trim()
if (!text.startsWith(PREFIX)) return false
@@ -9,7 +9,7 @@ class HelpCommand @Inject constructor() : ChatCommand {
override val usage = "/help"
override val description = "lists the commands you can run"
override fun run(ctx: CommandContext) {
override suspend fun run(ctx: CommandContext) {
ctx.commands.sortedBy { it.name }.forEach { ctx.reply("${it.usage} - ${it.description}") }
}
}
@@ -9,7 +9,7 @@ class PosCommand @Inject constructor() : ChatCommand {
override val usage = "/pos"
override val description = "shows the map and tile you are standing on"
override fun run(ctx: CommandContext) {
override suspend fun run(ctx: CommandContext) {
val s = ctx.state
ctx.reply(
"region ${s.regionId} bank ${s.bankId} map ${s.mapId} " +
@@ -18,7 +18,7 @@ class TestBattleCommand @Inject constructor(private val battleService: BattleSer
override val description = "starts a wild battle against the given species"
override val permission = CharacterPermissions.DEVELOPER
override fun run(ctx: CommandContext) {
override suspend fun run(ctx: CommandContext) {
val dexId = ctx.args.getOrNull(0)?.toIntOrNull() ?: DEFAULT_WILD_DEX
val level =
(ctx.args.getOrNull(1)?.toIntOrNull() ?: DEFAULT_WILD_LEVEL).coerceIn(
@@ -12,6 +12,7 @@ import java.util.concurrent.CopyOnWriteArrayList
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
@@ -19,6 +20,8 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
private val log = KotlinLogging.logger {}
@@ -61,6 +64,7 @@ constructor(
private val persisted = ConcurrentHashMap<Long, StoredCharacter>()
private val dirtySince = ConcurrentHashMap<Long, Long>()
private val pendingUnload = ConcurrentHashMap.newKeySet<Long>()
private val flushLocks = ConcurrentHashMap<Long, Mutex>()
/** Create a character with its own entity id and an empty party. */
suspend fun createCharacter(
@@ -178,12 +182,16 @@ constructor(
markDirty(characterId)
}
fun addPokemon(characterId: Long, pokemon: Pokemon) {
val stored = characters[characterId] ?: return
/** False when the monster could not be written, in which case the party is left as it was. */
suspend fun addPokemon(characterId: Long, pokemon: Pokemon): Boolean =
mutateDurably(
characterId,
// 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)
}
apply = { it.copy(pokemon = (it.pokemon + pokemon).toMutableList()) },
rollback = {
it.copy(pokemon = it.pokemon.filter { m -> m.id != pokemon.id }.toMutableList())
},
)
/** Replace one party monster by id, for example after a battle changed hp, xp, or level. */
fun updatePokemon(characterId: Long, updated: Pokemon) {
@@ -193,25 +201,35 @@ constructor(
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)
}
/** False when the change could not be written, in which case the balance is left as it was. */
suspend fun addMoney(characterId: Long, amount: Int): Boolean =
mutateDurably(
characterId,
apply = { it.copy(info = it.info.copy(money = it.info.money + amount)) },
// Undo the delta rather than restoring a snapshot, so a concurrent edit to another field
// of the same character survives.
rollback = { it.copy(info = it.info.copy(money = it.info.money - amount)) },
)
/** Add (or remove with a negative amount) one persisted bag stack. */
fun addItem(characterId: Long, itemId: Int, amount: Int): Boolean {
val stored = characters[characterId] ?: return false
val oldQuantity = stored.items[itemId] ?: 0
val newQuantity = oldQuantity + amount
if (newQuantity < 0) return false
/** False when the bag would go negative, or when the change could not be written. */
suspend fun addItem(characterId: Long, itemId: Int, amount: Int): Boolean =
mutateDurably(
characterId,
apply = { stored ->
val newQuantity = (stored.items[itemId] ?: 0) + amount
if (newQuantity < 0) return@mutateDurably null
val items = stored.items.toMutableMap()
if (newQuantity == 0) items.remove(itemId) else items[itemId] = newQuantity
characters[characterId] = stored.copy(items = items)
markDirty(characterId)
return true
}
stored.copy(items = items)
},
rollback = { stored ->
val reverted = (stored.items[itemId] ?: 0) - amount
val items = stored.items.toMutableMap()
if (reverted <= 0) items.remove(itemId) else items[itemId] = reverted
stored.copy(items = items)
},
)
/** Set (or clear with null) the runtime destination for MAP_DYNAMIC warps (setdynamicwarp). */
fun setDynamicWarp(characterId: Long, warp: DynamicWarp?) {
@@ -281,6 +299,32 @@ constructor(
flushScope.launch { flush(characterId) }
}
/**
* Marks the character dirty and writes it before returning. Anything a player can trade or spend
* goes through here, so a crash cannot lose an item that the client was already told it has.
* Position, hp and story progress do not, since replaying a few seconds of those costs nothing.
*/
/**
* Applies a change to something a player can trade or spend and writes it before returning. A
* failed write is undone by [rollback] and reported, so a caller never tells a player about an
* item, a coin or a monster the database did not accept.
*/
private suspend fun mutateDurably(
characterId: Long,
apply: (StoredCharacter) -> StoredCharacter?,
rollback: (StoredCharacter) -> StoredCharacter,
): Boolean =
lockFor(characterId).withLock {
val before = characters[characterId] ?: return@withLock false
val after = apply(before) ?: return@withLock false
characters[characterId] = after
markDirty(characterId)
if (flushLocked(characterId, allowEvict = false)) return@withLock true
characters[characterId]?.let { characters[characterId] = rollback(it) }
dirtySince.remove(characterId)
false
}
/**
* 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
@@ -319,7 +363,17 @@ constructor(
}
}
// Serialised per character. Without this a second flush takes the dirty marker, skips its own
// write and returns while the first is still inside saveChanges, so persistNow would promise a
// write it did not make.
private suspend fun flush(id: Long) {
lockFor(id).withLock { flushLocked(id, allowEvict = true) }
}
private fun lockFor(id: Long): Mutex = flushLocks.computeIfAbsent(id) { Mutex() }
/** True when the character is in the database, either because it was written or was not dirty. */
private suspend fun flushLocked(id: Long, allowEvict: Boolean): Boolean {
val since = dirtySince.remove(id)
val stored = characters[id]
if (since != null && stored != null) {
@@ -327,13 +381,19 @@ constructor(
repository.saveChanges(persisted[id], stored)
// The written instance, not the current one, so a racing mutation stays dirty.
persisted[id] = stored
} catch (e: CancellationException) {
// A disconnect cancelling the caller must not read as a failed write.
dirtySince.putIfAbsent(id, since)
throw e
} catch (e: Exception) {
log.warn(e) { "Failed to persist character $id, will retry" }
dirtySince.putIfAbsent(id, since)
return
return false
}
}
maybeEvict(id)
// A durable mutation must not evict the character its own caller is still working with.
if (allowEvict) maybeEvict(id)
return true
}
private fun maybeEvict(id: Long) {
@@ -344,6 +404,7 @@ constructor(
}
val stored = characters.remove(id) ?: return
persisted.remove(id)
flushLocks.remove(id)
charactersByUser.remove(stored.info.userId)
}
}
@@ -116,7 +116,11 @@ private fun FakeSession.startBattle(service: BattleService, dexId: Int = 19, lev
service.startWildBattle(this, dexId, level)
}
private fun FakeSession.act(service: BattleService, action: BattleAction, value: Short = 0) {
private suspend fun FakeSession.act(
service: BattleService,
action: BattleAction,
value: Short = 0,
) {
service.onBattleAction(PacketEvent(BattleActionSelectPacket(0, action, value, 0L, 0), this))
}
@@ -23,7 +23,7 @@ private class RecordingCommand(
override val description = "only for developers"
var ran = false
override fun run(ctx: CommandContext) {
override suspend fun run(ctx: CommandContext) {
ran = true
if (fail) error("boom")
}
@@ -73,7 +73,7 @@ class CharacterStoreCacheTest :
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 5000)
store.bumpMoneyLazily(id, 5000)
store.getCharacter(id)!!.info.money shouldBe 35000
repo.saved[id]!!.info.money shouldBe 30000
@@ -122,7 +122,7 @@ class CharacterStoreCacheTest :
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 1)
store.bumpMoneyLazily(id, 1)
repo.failNextSave = true
store.flushAll()
repo.saveCount.get() shouldBe 0
@@ -139,11 +139,11 @@ class CharacterStoreCacheTest :
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 1)
store.bumpMoneyLazily(id, 1)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30000
store.addMoney(id, 1)
store.bumpMoneyLazily(id, 1)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30001
}
@@ -155,11 +155,11 @@ class CharacterStoreCacheTest :
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 1)
store.bumpMoneyLazily(id, 1)
repo.failNextSave = true
store.flushAll()
store.addMoney(id, 2)
store.bumpMoneyLazily(id, 2)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30000
@@ -176,7 +176,7 @@ class CharacterStoreCacheTest :
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
store.getOrLoadCharacter(id).shouldNotBeNull()
store.addMoney(id, 3)
store.bumpMoneyLazily(id, 3)
store.flushAll()
repo.lastPrevious[id]!!.info.money shouldBe 30000
@@ -188,7 +188,7 @@ class CharacterStoreCacheTest :
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), this)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 5)
store.bumpMoneyLazily(id, 5)
store.unloadCharacterAsync(id)
advanceUntilIdle()
@@ -204,7 +204,7 @@ class CharacterStoreCacheTest :
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), this)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 1)
store.bumpMoneyLazily(id, 1)
repo.failNextSave = true
store.unloadCharacterAsync(id)
@@ -236,7 +236,7 @@ class CharacterStoreCacheTest :
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), this)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addMoney(id, 7)
store.bumpMoneyLazily(id, 7)
store.shutdown()
@@ -285,3 +285,11 @@ class CharacterStoreCacheTest :
}
}
})
/**
* Marks the character dirty without persisting, for tests about flush diffing rather than money.
*/
private fun CharacterStore.bumpMoneyLazily(id: Long, by: Int) {
val info = getCharacter(id)!!.info
updateCharacter(info.copy(money = info.money + by))
}
@@ -0,0 +1,213 @@
package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.Pokemon
import de.fiereu.openmmo.common.enums.CharacterGender
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.Region
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 java.time.LocalDateTime
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
/**
* Anything a player can trade or spend has to be in the database before the call returns. Position
* and hp may wait for a checkpoint, because replaying a few seconds of walking costs nothing, while
* an item the client has already been told about must not disappear in a crash.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class CharacterStoreDurabilityTest :
FunSpec({
test("granting an item persists it without waiting for a flush") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addItem(id, itemId = 17, amount = 3)
repo.saved[id]!!.items[17] shouldBe 3
}
}
test("spending money persists before the call returns") {
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, -500)
repo.saved[id]!!.info.money shouldBe 29500
}
}
test("acquiring a monster persists it before the call returns") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val created = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN)
store.addPokemon(created.info.id, caughtMonster(created.info.id))
repo.saved[created.info.id]!!.pokemon.size shouldBe 1
}
}
test("walking does not pay for a write, it waits for the checkpoint") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val created = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN)
val before = repo.saveCount.get()
store.updateCharacter(created.info.copy(positionX = 42))
repo.saveCount.get() shouldBe before
store.flushAll()
repo.saved[created.info.id]!!.info.positionX shouldBe 42
}
}
test("granting an item waits for a flush already in flight rather than riding on it") {
runTest {
val entered = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
val repo = GatedRepository(entered, release)
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
// A checkpoint is mid write when the grant arrives.
store.updateCharacter(store.getCharacter(id)!!.info.copy(positionX = 9))
store.flushCharacterAsync(id)
entered.await()
val grant = async { store.addItem(id, itemId = 17, amount = 1) }
advanceUntilIdle()
grant.isCompleted shouldBe false
release.complete(Unit)
grant.await() shouldBe true
repo.saved[id]!!.items[17] shouldBe 1
}
}
test("a write that fails grants nothing and says so") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
repo.failNextSave = true
store.addItem(id, itemId = 17, amount = 3) shouldBe false
// Neither the caller nor a later checkpoint may resurrect the refused grant.
store.getCharacter(id)!!.items[17] shouldBe null
store.flushAll()
repo.saved[id]!!.items[17] shouldBe null
}
}
test("a failed payment leaves the balance alone") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
repo.failNextSave = true
store.addMoney(id, 5000) shouldBe false
store.getCharacter(id)!!.info.money shouldBe 30000
}
}
test("granting an item does not evict the character its caller is still using") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
// The disconnect path has already asked for this character to be dropped.
store.unloadCharacterAsync(id)
store.addItem(id, itemId = 17, amount = 1) shouldBe true
store.getCharacter(id).shouldNotBeNull().items[17] shouldBe 1
}
}
test("a refused item change neither mutates nor writes") {
runTest {
val repo = FakeCharacterRepository()
val store = CharacterStore(repo, EntityIdService(), backgroundScope)
val id = store.createCharacter(1, "Ash", CharacterGender.MALE, Region.HOENN).info.id
store.addItem(id, itemId = 17, amount = 1)
val writes = repo.saveCount.get()
store.addItem(id, itemId = 17, amount = -5) shouldBe false
repo.saveCount.get() shouldBe writes
store.getCharacter(id).shouldNotBeNull().items[17] shouldBe 1
}
}
})
private fun caughtMonster(ownerId: Long): Pokemon =
Pokemon(
id = EntityIdService().newMonsterId(),
ownerId = ownerId,
container = PokemonContainer.PARTY,
containerSlot = 0,
dexId = 19,
seed = 0,
ot = "Ash",
nickname = "",
level = 3,
hp = 14,
xp = 27,
eVs = EVs(),
iVs = IVs(),
moves = listOf(),
isShiny = false,
hasHiddenAbility = false,
isAlpha = false,
isSecret = false,
isFatefulEncounter = false,
isRaidEncounter = false,
caughtAt = LocalDateTime.now(),
)
/** Holds the first write open so a grant can be raced against a checkpoint already in flight. */
private class GatedRepository(
private val entered: CompletableDeferred<Unit>,
private val release: CompletableDeferred<Unit>,
) : CharacterRepository {
private val delegate = FakeCharacterRepository()
private val writes = AtomicInteger(0)
val saved
get() = delegate.saved
override suspend fun loadByUser(userId: Int) = delegate.loadByUser(userId)
override suspend fun loadById(id: Long) = delegate.loadById(id)
override suspend fun insertAggregate(stored: StoredCharacter) = delegate.insertAggregate(stored)
override suspend fun deleteById(userId: Int, id: Long) = delegate.deleteById(userId, id)
override suspend fun saveChanges(previous: StoredCharacter?, current: StoredCharacter) {
if (writes.incrementAndGet() == 1) {
entered.complete(Unit)
release.await()
}
delegate.saveChanges(previous, current)
}
}