diff --git a/.env.example b/.env.example index 18f3bdb..03a5c8a 100644 --- a/.env.example +++ b/.env.example @@ -1,14 +1,18 @@ # Copy this file to `.env` and adjust the values for your environment. # `.env` is gitignored and must never be committed. +LOGIN_DB_HOST=localhost LOGIN_DB_PORT=20011 LOGIN_DB_NAME=openmmo_login_db LOGIN_DB_USER=openmmo_login_user LOGIN_DB_PASSWORD=changeMe! +LOGIN_DB_SEED_DEV=true +GAME_DB_HOST=localhost GAME_DB_PORT=20021 GAME_DB_NAME=openmmo_game_db GAME_DB_USER=openmmo_game_user GAME_DB_PASSWORD=changeMe! +GAME_DB_SEED_DEV=true OPENMMO_SESSION_SECRET= \ No newline at end of file diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index c4a79c1..874e724 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -12,6 +12,10 @@ gradlePlugin { id = "buildsrc.convention.jte-codegen" implementationClass = "buildsrc.convention.JteCodegenPlugin" } + create("jooqDb") { + id = "buildsrc.convention.jooq-db" + implementationClass = "buildsrc.convention.JooqDbPlugin" + } } } @@ -19,5 +23,7 @@ dependencies { implementation(libs.kotlinGradlePlugin) implementation(libs.spotlessGradlePlugin) implementation(libs.sonarlintGradlePlugin) + implementation(libs.jooqCodegenGradlePlugin) + implementation(libs.jooq.meta) implementation(libs.junit5) } diff --git a/buildSrc/src/main/kotlin/JooqDb.kt b/buildSrc/src/main/kotlin/JooqDb.kt new file mode 100644 index 0000000..95bff7a --- /dev/null +++ b/buildSrc/src/main/kotlin/JooqDb.kt @@ -0,0 +1,118 @@ +package buildsrc.convention + +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.artifacts.VersionCatalogsExtension +import org.gradle.api.provider.Property +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.SourceSetContainer +import org.gradle.api.tasks.bundling.Jar +import org.gradle.kotlin.dsl.create +import org.gradle.kotlin.dsl.getByType +import org.gradle.kotlin.dsl.named +import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension +import org.jooq.codegen.gradle.CodegenPluginExtension +import org.jooq.meta.jaxb.Database +import org.jooq.meta.jaxb.Generate +import org.jooq.meta.jaxb.Generator +import org.jooq.meta.jaxb.Property as JooqProperty +import org.jooq.meta.jaxb.Target + +private const val MIGRATIONS_DIR = "src/main/resources/db/migration" + +abstract class JooqDbExtension { + abstract val packageName: Property +} + +/** + * Generates jOOQ classes from the module's Flyway migrations without a live database and compiles + * them in their own `jooq` source set. Also adds the runtime database dependencies. + */ +class JooqDbPlugin : Plugin { + override fun apply(project: Project) { + project.pluginManager.apply("org.jooq.jooq-codegen-gradle") + val ext = project.extensions.create("jooqDb") + + project.afterEvaluate { + project.extensions.getByType().configuration { + generator = + Generator() + .withName("org.jooq.codegen.KotlinGenerator") + .withDatabase( + Database() + .withName("org.jooq.meta.extensions.ddl.DDLDatabase") + .withProperties( + JooqProperty().withKey("scripts").withValue("$MIGRATIONS_DIR/*.sql"), + JooqProperty().withKey("sort").withValue("flyway"), + JooqProperty().withKey("unqualifiedSchema").withValue("none"), + JooqProperty().withKey("defaultNameCase").withValue("lower"), + )) + .withGenerate( + Generate() + .withKotlinNotNullRecordAttributes(true) + .withKotlinNotNullPojoAttributes(true) + .withPojos(false) + .withDaos(false)) + .withTarget( + Target() + .withPackageName(ext.packageName.get()) + .withDirectory("build/generated-sources/jooq")) + } + } + + // The jOOQ plugin does not track the files behind the DDLDatabase "scripts" property. + // Declare them as inputs so up-to-date checks and caching stay correct. + project.tasks.named("jooqCodegen") { + inputs + .dir(MIGRATIONS_DIR) + .withPropertyName("flywayMigrations") + .withPathSensitivity(PathSensitivity.RELATIVE) + } + + val sourceSets = project.extensions.getByType() + val jooqSourceSet = sourceSets.create("jooq") + project.extensions + .getByType() + .sourceSets + .getByName("jooq") + .kotlin + .srcDir(project.tasks.named("jooqCodegen")) + + // Realizing the codegen task adds its output to the main source set. Do it now and undo + // the srcDir, so the generated classes only compile in the jooq source set. + project.afterEvaluate { + project.tasks.named("jooqCodegen").get() + val mainJava = sourceSets.getByName("main").java + mainJava.setSrcDirs( + mainJava.srcDirs.filterNot { + it.invariantSeparatorsPath.endsWith("generated-sources/jooq") + }) + } + + listOf("main", "test").forEach { name -> + sourceSets.getByName(name).apply { + compileClasspath += jooqSourceSet.output + runtimeClasspath += jooqSourceSet.output + } + } + project.tasks.named("jar") { from(jooqSourceSet.output) } + + val libs = project.extensions.getByType().named("libs") + fun lib(alias: String) = + libs.findLibrary(alias).orElseThrow { IllegalStateException("missing catalog entry $alias") } + with(project.dependencies) { + addProvider("jooqCodegen", lib("jooq-meta-extensions")) + addProvider("jooqImplementation", lib("jooq")) + addProvider("jooqImplementation", lib("jooq-kotlin")) + addProvider("implementation", lib("jooq")) + addProvider("implementation", lib("jooq-kotlin")) + addProvider("implementation", lib("hikaricp")) + addProvider("implementation", lib("flyway-core")) + addProvider("runtimeOnly", lib("flyway-postgresql")) + addProvider("runtimeOnly", lib("postgresql")) + addProvider("testImplementation", lib("testcontainers-postgresql")) + addProvider("testImplementation", lib("testcontainers-junit")) + addProvider("testRuntimeOnly", lib("postgresql")) + } + } +} diff --git a/buildSrc/src/main/kotlin/keys.gradle.kts b/buildSrc/src/main/kotlin/keys.gradle.kts index 64e3d47..2b38f6e 100644 --- a/buildSrc/src/main/kotlin/keys.gradle.kts +++ b/buildSrc/src/main/kotlin/keys.gradle.kts @@ -65,5 +65,7 @@ tasks.register("copyKeys") { val keyCopyTasks = listOf("copyPublicKeyChat", "copyPrivateKeyChat", "copyPublicKeyGame", "copyPrivateKeyGame") -tasks.matching { it.name.startsWith("spotless") || it.name.startsWith("sonarlint") } +tasks.matching { + it.name.startsWith("spotless") || it.name.startsWith("sonarlint") || it.name == "jooqCodegen" + } .configureEach { mustRunAfter(keyCopyTasks) } \ No newline at end of file diff --git a/docs/src/content/docs/concepts/database.md b/docs/src/content/docs/concepts/database.md new file mode 100644 index 0000000..7fba46c --- /dev/null +++ b/docs/src/content/docs/concepts/database.md @@ -0,0 +1,66 @@ +--- +title: The database +description: How persistence works and how dev data is seeded. +--- + +OpenMMO uses two PostgreSQL databases, matching the two servers: + +- **login-db**: accounts (`users` table), owned by `server.login`. +- **game-db**: characters, pokemon, and items, owned by `server.game`. + +They stay separate on purpose. The game server never looks up accounts, it +trusts the `userId` handed over through the session token. That is also why +`characters.user_id` has no foreign key: it points into the other database. + +Both are wired the same way: HikariCP for connection pooling, Flyway for +migrations, and jOOQ for queries. + +## Migrations are the source of truth + +The schema lives as plain SQL in each server's +`src/main/resources/db/migration/` (`V1__...`, `V2__...`). Those files are +used twice: + +- **At build time** jOOQ parses them with `DDLDatabase` and generates Kotlin + classes into the module's `jooq` source set. No database or Docker is + needed to build. +- **At server start** `main()` runs Flyway against the real database before + anything listens. A missing or broken database stops the server right there. + +To change the schema, add a new `V__short_name.sql` file and rebuild. +Never edit an already merged migration. Keep the DDL standard SQL, the jOOQ +parser does not know exotic Postgres extensions. + +## Memory is the live version + +The game server does not query the database during gameplay. +`CharacterStore` loads a character when its player logs in and all reads and +writes hit memory. Changes mark the character dirty, and a background flusher +writes dirty characters back after a short debounce. Warps and disconnects +flush immediately, and a disconnect also evicts the character from memory +once its last write succeeded. So the database always trails memory by a few +seconds at most, and only connected players are cached. + +## Dev data seeding + +Dev seed data (the `admin`/`test` accounts and the `Test`/`Test2` characters) +does NOT belong in `db/migration`. Anything there runs in every environment, +including production. Seeds live in a separate Flyway location: + +- Files go into `src/main/resources/db/dev/`. +- They are repeatable migrations (`R__seed_something.sql`), not versioned + ones, so they never conflict with real schema versions. +- Every statement must be idempotent, because repeatable migrations run again + whenever their file changes. Use `ON CONFLICT DO NOTHING` on inserts. +- Fixed ids in seed files must keep the entity tag in the low 16 bits + (0x9000 for characters, 0xC000 for monsters). Runtime ids carry a timestamp + head, so low fixed values can never collide with them. + +The `db/dev` location is only applied when `db.seedDev` is enabled. It +defaults to true for local development and is turned off in production with +the `LOGIN_DB_SEED_DEV=false` and `GAME_DB_SEED_DEV=false` environment +variables. + +To add more dev data, extend an existing `R__` file or add a new one, keep it +idempotent, and restart the server. Flyway reapplies the changed file on the +next start. diff --git a/docs/src/content/docs/concepts/index.md b/docs/src/content/docs/concepts/index.md index ef94e22..aee1da4 100644 --- a/docs/src/content/docs/concepts/index.md +++ b/docs/src/content/docs/concepts/index.md @@ -5,5 +5,7 @@ description: Short explanations of the systems that make up OpenMMO. Short explanations of the systems that make up OpenMMO. +- [The database](database/): how persistence works and how dev data is + seeded. - [The InterestManager](interest-manager/): how packets reach the right players instead of everyone online. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 3cbfdd1..40d584c 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -16,6 +16,8 @@ mockk = "1.14.11" jooq = "3.21.6" postgresql = "42.7.13" flyway = "11.20.3" +hikaricp = "7.0.2" +testcontainers = "1.21.3" netty = "4.2.16.Final" typesafe-config = "1.4.9" dagger = "2.60.1" @@ -25,6 +27,7 @@ dotenv = "4.0.0" [libraries] kotlinGradlePlugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } +jooqCodegenGradlePlugin = { module = "org.jooq:jooq-codegen-gradle", version.ref = "jooq" } spotlessGradlePlugin = { module = "com.diffplug.spotless:spotless-plugin-gradle", version.ref = "spotless" } sonarlintGradlePlugin = { module = "name.remal.sonarlint:name.remal.sonarlint.gradle.plugin", version.ref = "sonarlint" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" } @@ -49,9 +52,13 @@ jooq = { module = "org.jooq:jooq", version.ref = "jooq" } jooq-kotlin = { module = "org.jooq:jooq-kotlin", version.ref = "jooq" } jooq-meta = { module = "org.jooq:jooq-meta", version.ref = "jooq" } jooq-codegen = { module = "org.jooq:jooq-codegen", version.ref = "jooq" } +jooq-meta-extensions = { module = "org.jooq:jooq-meta-extensions", version.ref = "jooq" } postgresql = { module = "org.postgresql:postgresql", version.ref = "postgresql" } flyway-core = { module = "org.flywaydb:flyway-core", version.ref = "flyway" } flyway-postgresql = { module = "org.flywaydb:flyway-database-postgresql", version.ref = "flyway" } +hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "hikaricp" } +testcontainers-postgresql = { module = "org.testcontainers:postgresql", version.ref = "testcontainers" } +testcontainers-junit = { module = "org.testcontainers:junit-jupiter", version.ref = "testcontainers" } netty = { module = "io.netty:netty-all", version.ref = "netty" } typesafe-config = { module = "com.typesafe:config", version.ref = "typesafe-config" } dagger = { module = "com.google.dagger:dagger", version.ref = "dagger" } diff --git a/network/src/test/kotlin/de/fiereu/network/handlers/FrameAndChecksumTest.kt b/network/src/test/kotlin/de/fiereu/network/handlers/FrameAndChecksumTest.kt index df3cb2f..74cdb40 100644 --- a/network/src/test/kotlin/de/fiereu/network/handlers/FrameAndChecksumTest.kt +++ b/network/src/test/kotlin/de/fiereu/network/handlers/FrameAndChecksumTest.kt @@ -53,7 +53,7 @@ class FrameAndChecksumTest : out.readableBytes() shouldBe 4 } - test("ChecksumFrameEncoder appends tag; decoder strips it") { + test("ChecksumFrameEncoder appends the tag and the decoder strips it") { val enc = EmbeddedChannel(ChecksumFrameEncoder(Crc16Checksum())) enc.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(1, 2, 3, 4))) val withTag = enc.drainOutbound() diff --git a/server.game/build.gradle.kts b/server.game/build.gradle.kts index eba2ec6..0608292 100644 --- a/server.game/build.gradle.kts +++ b/server.game/build.gradle.kts @@ -4,6 +4,7 @@ plugins { id("buildsrc.convention.spotless") id("buildsrc.convention.sonarlint") id("buildsrc.common.keys") + id("buildsrc.convention.jooq-db") alias(libs.plugins.ksp) } @@ -13,6 +14,8 @@ version = "0.1.0" application { mainClass.set("de.fiereu.openmmo.server.game.MainKt") } +jooqDb { packageName = "de.fiereu.openmmo.db.game" } + dependencies { api(project(":network")) api(project(":protocols.game")) @@ -34,10 +37,12 @@ dependencies { tasks.named("run") { listOf( "OPENMMO_SESSION_SECRET", + "GAME_DB_HOST", "GAME_DB_PORT", "GAME_DB_NAME", "GAME_DB_USER", - "GAME_DB_PASSWORD") + "GAME_DB_PASSWORD", + "GAME_DB_SEED_DEV") .forEach { key -> env.fetchOrNull(key)?.let { environment(key, it) } } } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/Main.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/Main.kt index 65cefc3..3ad283c 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/Main.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/Main.kt @@ -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() } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt index 24e2109..a39c495 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/ConfigLoader.kt @@ -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"), + ), ) } } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/DbConfig.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/DbConfig.kt new file mode 100644 index 0000000..ee978c1 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/DbConfig.kt @@ -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" +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt index f29065c..f2e44d8 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/config/GameServerConfig.kt @@ -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 } } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/db/DatabaseBootstrap.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/db/DatabaseBootstrap.kt new file mode 100644 index 0000000..7546702 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/db/DatabaseBootstrap.kt @@ -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" } + } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerComponent.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerComponent.kt index 58b4eef..fb442cc 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerComponent.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerComponent.kt @@ -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 diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt index 7557a86..4207b05 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/di/GameServerModule.kt @@ -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) } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt index a426cf3..1057c73 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/handler/GameAppHandler.kt @@ -161,6 +161,7 @@ constructor( if (charId != null) { presenceService.leave(session) sessionRegistry.unbindCharacter(charId) + characterStore.unloadCharacterAsync(charId) } multiplayerService.broadcastMessage( ChatMessagePacket( diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt index e31e58c..25fae4c 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/BattleService.kt @@ -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() @@ -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, diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt index 45f37d9..907faf3 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/LoginService.kt @@ -98,20 +98,25 @@ constructor( ctx.send(JoinResponsePacket.acceptNow(playtime = 1337, rewardPoints = 420, balance = 187)) } - fun onCreateCharacter(event: PacketEvent) { + suspend fun onCreateCharacter(event: PacketEvent) { 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) { + suspend fun onCharacterRequest(event: PacketEvent) { 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) { + suspend fun onCharacterSelected(event: PacketEvent) { 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 diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt index 1b800b8..1341b93 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/MovementService.kt @@ -179,6 +179,7 @@ constructor( targetBank, targetMap, ) + characterStore.flushCharacterAsync(charId) presenceService.refresh(ctx) mapLoadService.preloadConnectedMaps(ctx, map, depth = 1) diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt index a201783..e1fa912 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/services/WarpService.kt @@ -94,6 +94,7 @@ constructor( positionY = offsetY.toShort(), ) characterStore.updateCharacter(newInfo) + characterStore.flushCharacterAsync(charId) if (state != null) { state.regionId = warp.targetRegionId.toInt() diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/CharacterRepository.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/CharacterRepository.kt new file mode 100644 index 0000000..a873813 --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/CharacterRepository.kt @@ -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 + + 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 = + 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): List { + if (rows.isEmpty()) return emptyList() + val ids = rows.map { it.id } + val monstersByOwner: Map> = + 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> = + 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) } +} diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/CharacterStore.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/CharacterStore.kt index 41e81b6..c16df22 100644 --- a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/CharacterStore.kt +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/CharacterStore.kt @@ -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, ) +/** + * 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() - private val charactersByUser = ConcurrentHashMap>() - 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>() + private val dirtySince = ConcurrentHashMap() + private val pendingUnload = ConcurrentHashMap.newKeySet() /** 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 { - 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 { + val cachedIds: List? = 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) - } } diff --git a/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/EntityIdService.kt b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/EntityIdService.kt new file mode 100644 index 0000000..e40487c --- /dev/null +++ b/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/storage/EntityIdService.kt @@ -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 + } +} diff --git a/server.game/src/main/resources/application.conf b/server.game/src/main/resources/application.conf index ef532ef..d5c743f 100644 --- a/server.game/src/main/resources/application.conf +++ b/server.game/src/main/resources/application.conf @@ -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} +} diff --git a/server.game/src/main/resources/db/dev/R__seed_dev_characters.sql b/server.game/src/main/resources/db/dev/R__seed_dev_characters.sql new file mode 100644 index 0000000..1664ae9 --- /dev/null +++ b/server.game/src/main/resources/db/dev/R__seed_dev_characters.sql @@ -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; diff --git a/server.game/src/main/resources/db/migration/V1__create_game_schema.sql b/server.game/src/main/resources/db/migration/V1__create_game_schema.sql new file mode 100644 index 0000000..091b5df --- /dev/null +++ b/server.game/src/main/resources/db/migration/V1__create_game_schema.sql @@ -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) +); diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/PresenceServiceTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/PresenceServiceTest.kt index e4dfa0f..ee5a56d 100644 --- a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/PresenceServiceTest.kt +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/services/PresenceServiceTest.kt @@ -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 { - 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) } diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/CharacterRepositoryIT.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/CharacterRepositoryIT.kt new file mode 100644 index 0000000..08680f0 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/CharacterRepositoryIT.kt @@ -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("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) + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/CharacterStoreCacheTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/CharacterStoreCacheTest.kt new file mode 100644 index 0000000..75ec6d8 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/CharacterStoreCacheTest.kt @@ -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() + } + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/EntityIdServiceTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/EntityIdServiceTest.kt new file mode 100644 index 0000000..c4125cd --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/EntityIdServiceTest.kt @@ -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 + } + }) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/GuildStoreTest.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/GuildStoreTest.kt index 2fcf42f..b1ae42c 100644 --- a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/GuildStoreTest.kt +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/storage/GuildStoreTest.kt @@ -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) diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/testsupport/DockerAvailable.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/testsupport/DockerAvailable.kt new file mode 100644 index 0000000..75e8caf --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/testsupport/DockerAvailable.kt @@ -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): Boolean = + runCatching { DockerClientFactory.instance().isDockerAvailable() }.getOrDefault(false) +} diff --git a/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/testsupport/FakeCharacterRepository.kt b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/testsupport/FakeCharacterRepository.kt new file mode 100644 index 0000000..f450a39 --- /dev/null +++ b/server.game/src/test/kotlin/de/fiereu/openmmo/server/game/testsupport/FakeCharacterRepository.kt @@ -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() + val saveCount = AtomicInteger(0) + var failNextSave = false + + override suspend fun loadByUser(userId: Int): List = + 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 + } +} diff --git a/server.login/build.gradle.kts b/server.login/build.gradle.kts index 8622ea0..54dbfba 100644 --- a/server.login/build.gradle.kts +++ b/server.login/build.gradle.kts @@ -4,6 +4,7 @@ plugins { id("buildsrc.convention.spotless") id("buildsrc.convention.sonarlint") id("buildsrc.common.keys") + id("buildsrc.convention.jooq-db") alias(libs.plugins.ksp) } @@ -13,6 +14,8 @@ version = "0.1.0" application { mainClass.set("de.fiereu.openmmo.server.login.MainKt") } +jooqDb { packageName = "de.fiereu.openmmo.db.login" } + dependencies { api(project(":network")) api(project(":protocols.login")) @@ -33,10 +36,12 @@ dependencies { tasks.named("run") { listOf( "OPENMMO_SESSION_SECRET", + "LOGIN_DB_HOST", "LOGIN_DB_PORT", "LOGIN_DB_NAME", "LOGIN_DB_USER", - "LOGIN_DB_PASSWORD") + "LOGIN_DB_PASSWORD", + "LOGIN_DB_SEED_DEV") .forEach { key -> env.fetchOrNull(key)?.let { environment(key, it) } } } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/Main.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/Main.kt index 63a338e..05e7e76 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/Main.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/Main.kt @@ -6,5 +6,6 @@ import de.fiereu.openmmo.server.login.di.DaggerLoginServerComponent fun main() { val config = ConfigLoader.load() val component = DaggerLoginServerComponent.factory().create(config) + component.databaseBootstrap().migrate() component.server().start() } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStore.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStore.kt new file mode 100644 index 0000000..2b59c90 --- /dev/null +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStore.kt @@ -0,0 +1,48 @@ +package de.fiereu.openmmo.server.login.auth + +import de.fiereu.openmmo.common.enums.LoginState +import de.fiereu.openmmo.db.login.tables.references.USERS +import javax.inject.Inject +import javax.inject.Named +import javax.inject.Singleton +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext +import org.jooq.DSLContext + +@Singleton +class JooqUserStore +@Inject +constructor( + private val dsl: DSLContext, + @param:Named("db") private val dispatcher: CoroutineDispatcher, +) : UserService { + + override suspend fun authenticate(username: String, password: String): UserService.AuthResult = + withContext(dispatcher) { + val user = dsl.selectFrom(USERS).where(USERS.USERNAME.eq(username.lowercase())).fetchOne() + if (user == null || user.passwordHash != password) { + UserService.AuthResult(LoginState.INVALID_PASSWORD) + } else { + UserService.AuthResult(LoginState.AUTHED, user.id) + } + } + + override suspend fun getUserId(username: String): Int? = + withContext(dispatcher) { + dsl.select(USERS.ID) + .from(USERS) + .where(USERS.USERNAME.eq(username.lowercase())) + .fetchOne(USERS.ID) + } + + suspend fun addUser(username: String, password: String): Int = + withContext(dispatcher) { + dsl.insertInto(USERS) + .set(USERS.USERNAME, username.lowercase()) + .set(USERS.DISPLAY_NAME, username) + .set(USERS.PASSWORD_HASH, sha1Hex(password)) + .returning(USERS.ID) + .fetchSingle() + .id!! + } +} diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt index 1d2ad40..8f6fc0e 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/auth/UserService.kt @@ -10,9 +10,15 @@ import javax.inject.Singleton interface UserService { data class AuthResult(val state: LoginState, val userId: Int? = null) - fun authenticate(username: String, password: String): AuthResult + suspend fun authenticate(username: String, password: String): AuthResult - fun getUserId(username: String): Int? + suspend fun getUserId(username: String): Int? +} + +@Suppress("kotlin:S4790") +internal fun sha1Hex(value: String): String { + val sha1 = MessageDigest.getInstance("SHA-1").digest(value.toByteArray()) + return sha1.joinToString("") { "%02x".format(it) } } @Singleton @@ -28,16 +34,13 @@ class InMemoryUserStore @Inject constructor() : UserService { addUser("test", "test") } - @Suppress("kotlin:S4790") fun addUser(username: String, password: String): Int { val id = nextId.getAndIncrement() - val sha1 = MessageDigest.getInstance("SHA-1").digest(password.toByteArray()) - val hex = sha1.joinToString("") { "%02x".format(it) } - users[username.lowercase()] = UserInfo(id, hex, username) + users[username.lowercase()] = UserInfo(id, sha1Hex(password), username) return id } - override fun authenticate(username: String, password: String): UserService.AuthResult { + override suspend fun authenticate(username: String, password: String): UserService.AuthResult { val user = users[username.lowercase()] ?: return UserService.AuthResult(LoginState.INVALID_PASSWORD) if (user.passwordHash != password) { @@ -46,5 +49,5 @@ class InMemoryUserStore @Inject constructor() : UserService { return UserService.AuthResult(LoginState.AUTHED, user.id) } - override fun getUserId(username: String): Int? = users[username.lowercase()]?.id + override suspend fun getUserId(username: String): Int? = users[username.lowercase()]?.id } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt index c85d349..48a0722 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/ConfigLoader.kt @@ -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"), + ), ) } } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/DbConfig.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/DbConfig.kt new file mode 100644 index 0000000..fdb47f1 --- /dev/null +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/DbConfig.kt @@ -0,0 +1,14 @@ +package de.fiereu.openmmo.server.login.config + +data class DbConfig( + val host: String = "localhost", + val port: Int = 20011, + val name: String = "openmmo_login_db", + val user: String = "openmmo_login_user", + val password: String = "changeMe!", + val poolSize: Int = 4, + val seedDev: Boolean = true, +) { + val jdbcUrl: String + get() = "jdbc:postgresql://$host:$port/$name" +} diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt index 63d6385..bf04a23 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/config/LoginServerConfig.kt @@ -6,6 +6,7 @@ data class LoginServerConfig( val checksumSize: Int, val rootKeyResource: String, val sessionSecret: ByteArray, + val db: DbConfig = DbConfig(), ) { override fun equals(other: Any?): Boolean = other is LoginServerConfig && @@ -13,7 +14,8 @@ data class LoginServerConfig( 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 LoginServerConfig( h = h * 31 + checksumSize h = h * 31 + rootKeyResource.hashCode() h = h * 31 + sessionSecret.contentHashCode() + h = h * 31 + db.hashCode() return h } } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/db/DatabaseBootstrap.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/db/DatabaseBootstrap.kt new file mode 100644 index 0000000..bf1e3e1 --- /dev/null +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/db/DatabaseBootstrap.kt @@ -0,0 +1,33 @@ +package de.fiereu.openmmo.server.login.db + +import de.fiereu.openmmo.server.login.config.LoginServerConfig +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: LoginServerConfig, +) { + + 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" } + } +} diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerComponent.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerComponent.kt index ccaf6a7..b288d93 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerComponent.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerComponent.kt @@ -4,6 +4,7 @@ import dagger.BindsInstance import dagger.Component import de.fiereu.openmmo.server.login.LoginServer import de.fiereu.openmmo.server.login.config.LoginServerConfig +import de.fiereu.openmmo.server.login.db.DatabaseBootstrap import de.fiereu.openmmo.server.login.handler.LoginAppHandler import javax.inject.Provider import javax.inject.Singleton @@ -16,6 +17,8 @@ interface LoginServerComponent { fun handlerProvider(): Provider + fun databaseBootstrap(): DatabaseBootstrap + @Component.Factory fun interface Factory { fun create(@BindsInstance config: LoginServerConfig): LoginServerComponent diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt index f960bc1..9fda9f8 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/di/LoginServerModule.kt @@ -1,12 +1,14 @@ package de.fiereu.openmmo.server.login.di +import com.zaxxer.hikari.HikariConfig +import com.zaxxer.hikari.HikariDataSource import dagger.Binds import dagger.Module import dagger.Provides import de.fiereu.openmmo.common.auth.SessionTokenIssuer import de.fiereu.openmmo.common.io.PemKeyLoader import de.fiereu.openmmo.common.io.resource -import de.fiereu.openmmo.server.login.auth.InMemoryUserStore +import de.fiereu.openmmo.server.login.auth.JooqUserStore import de.fiereu.openmmo.server.login.auth.UserService import de.fiereu.openmmo.server.login.config.LoginServerConfig import io.netty.channel.EventLoopGroup @@ -15,14 +17,19 @@ 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 abstract class LoginServerModule { - @Binds @Singleton abstract fun userService(impl: InMemoryUserStore): UserService + @Binds @Singleton abstract fun userService(impl: JooqUserStore): UserService companion object { @Provides @@ -48,5 +55,29 @@ abstract class LoginServerModule { @Provides @Singleton fun coroutineScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + // 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: LoginServerConfig): 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: LoginServerConfig): CoroutineDispatcher = + Dispatchers.IO.limitedParallelism(config.db.poolSize) } } diff --git a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt index 447067a..d045c88 100644 --- a/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt +++ b/server.login/src/main/kotlin/de/fiereu/openmmo/server/login/handler/LoginAppHandler.kt @@ -38,7 +38,7 @@ constructor( onSuspend { event -> onJoinGameServer(event) } } - private fun onLoginRequest(event: PacketEvent) { + private suspend fun onLoginRequest(event: PacketEvent) { val packet = event.packet val method = packet.method if (method !is PasswordLogin) { diff --git a/server.login/src/main/resources/application.conf b/server.login/src/main/resources/application.conf index b8ca8c6..ff2c553 100644 --- a/server.login/src/main/resources/application.conf +++ b/server.login/src/main/resources/application.conf @@ -6,3 +6,21 @@ server { sessionSecret = "dev-only-secret-do-not-use-in-production" sessionSecret = ${?OPENMMO_SESSION_SECRET} } + +db { + host = "localhost" + host = ${?LOGIN_DB_HOST} + port = 20011 + port = ${?LOGIN_DB_PORT} + name = "openmmo_login_db" + name = ${?LOGIN_DB_NAME} + user = "openmmo_login_user" + user = ${?LOGIN_DB_USER} + password = "changeMe!" + password = ${?LOGIN_DB_PASSWORD} + poolSize = 4 + poolSize = ${?LOGIN_DB_POOL_SIZE} + # Applies the dev seed data in db/dev. Turn off in production. + seedDev = true + seedDev = ${?LOGIN_DB_SEED_DEV} +} diff --git a/server.login/src/main/resources/db/dev/R__seed_dev_users.sql b/server.login/src/main/resources/db/dev/R__seed_dev_users.sql new file mode 100644 index 0000000..92550de --- /dev/null +++ b/server.login/src/main/resources/db/dev/R__seed_dev_users.sql @@ -0,0 +1,7 @@ +-- Dev accounts admin/admin and test/test. The hashes are the SHA-1 the client sends. +-- Only applied when db.seedDev is enabled, never in production. +INSERT INTO users (username, display_name, password_hash) +VALUES + ('admin', 'admin', 'd033e22ae348aeb5660fc2140aec35850c4da997'), + ('test', 'test', 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3') +ON CONFLICT (username) DO NOTHING; diff --git a/server.login/src/main/resources/db/migration/V1__create_users.sql b/server.login/src/main/resources/db/migration/V1__create_users.sql new file mode 100644 index 0000000..e84e98a --- /dev/null +++ b/server.login/src/main/resources/db/migration/V1__create_users.sql @@ -0,0 +1,10 @@ +CREATE TABLE users ( + id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + -- Always lowercase. Lookups go through this column. + username VARCHAR(32) NOT NULL, + display_name VARCHAR(32) NOT NULL, + -- Unsalted SHA-1 hex. The client already hashes the password before sending it. + password_hash VARCHAR(40) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_users_username UNIQUE (username) +); diff --git a/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStoreIT.kt b/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStoreIT.kt new file mode 100644 index 0000000..e90d094 --- /dev/null +++ b/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/auth/JooqUserStoreIT.kt @@ -0,0 +1,59 @@ +package de.fiereu.openmmo.server.login.auth + +import de.fiereu.openmmo.common.enums.LoginState +import de.fiereu.openmmo.server.login.testsupport.DockerAvailable +import io.kotest.core.annotation.EnabledIf +import io.kotest.core.spec.style.FunSpec +import io.kotest.matchers.shouldBe +import kotlinx.coroutines.Dispatchers +import org.flywaydb.core.Flyway +import org.jooq.impl.DSL +import org.testcontainers.containers.PostgreSQLContainer + +@EnabledIf(DockerAvailable::class) +class JooqUserStoreIT : + FunSpec({ + val container = PostgreSQLContainer("postgres:18") + lateinit var store: JooqUserStore + + 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) + store = JooqUserStore(dsl, Dispatchers.IO) + } + + afterSpec { container.stop() } + + test("the seed migration provides admin and test") { + store.getUserId("admin") shouldBe 1 + store.getUserId("test") shouldBe 2 + } + + test("authenticate succeeds with the hashed password") { + val result = store.authenticate("admin", sha1Hex("admin")) + result.state shouldBe LoginState.AUTHED + result.userId shouldBe 1 + } + + test("authenticate is case-insensitive on username") { + store.authenticate("ADMIN", sha1Hex("admin")).state shouldBe LoginState.AUTHED + } + + test("authenticate fails for a wrong password") { + store.authenticate("admin", sha1Hex("nope")).state shouldBe LoginState.INVALID_PASSWORD + } + + test("authenticate fails for an unknown user") { + store.authenticate("nobody", sha1Hex("pw")).state shouldBe LoginState.INVALID_PASSWORD + } + + test("addUser returns the generated id and getUserId finds it") { + val id = store.addUser("Alice", "pw") + store.getUserId("alice") shouldBe id + } + }) diff --git a/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/testsupport/DockerAvailable.kt b/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/testsupport/DockerAvailable.kt new file mode 100644 index 0000000..dd1dfa6 --- /dev/null +++ b/server.login/src/test/kotlin/de/fiereu/openmmo/server/login/testsupport/DockerAvailable.kt @@ -0,0 +1,12 @@ +package de.fiereu.openmmo.server.login.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): Boolean = + runCatching { DockerClientFactory.instance().isDockerAvailable() }.getOrDefault(false) +}