forked from mtusi2026/mtusi2026lab2
Completed for a grade of four
This commit is contained in:
@@ -6,6 +6,7 @@ import com.mtusi.messenger.main.plugins.configureContentNegotiation
|
||||
import com.mtusi.messenger.main.plugins.configureDatabase
|
||||
import com.mtusi.messenger.main.plugins.configureDefaultHeaders
|
||||
import com.mtusi.messenger.main.plugins.configureKoin
|
||||
import com.mtusi.messenger.main.plugins.configureRedis
|
||||
import com.mtusi.messenger.main.plugins.configureRequestId
|
||||
import com.mtusi.messenger.main.plugins.configureRouting
|
||||
import com.mtusi.messenger.main.plugins.configureStatusPages
|
||||
@@ -18,6 +19,7 @@ fun Application.module() {
|
||||
|
||||
configureKoin()
|
||||
configureDatabase()
|
||||
configureRedis()
|
||||
|
||||
configureContentNegotiation()
|
||||
configureDefaultHeaders()
|
||||
|
||||
@@ -4,5 +4,6 @@ interface AuthenticationConfig {
|
||||
|
||||
val realm: String
|
||||
val sessionTtlSeconds: Long
|
||||
val sessionCacheTtlSeconds: Long
|
||||
|
||||
}
|
||||
|
||||
+2
-1
@@ -5,5 +5,6 @@ import kotlinx.serialization.Serializable
|
||||
@Serializable
|
||||
data class SerialAuthenticationConfig(
|
||||
override val realm: String,
|
||||
override val sessionTtlSeconds: Long
|
||||
override val sessionTtlSeconds: Long,
|
||||
override val sessionCacheTtlSeconds: Long
|
||||
) : AuthenticationConfig
|
||||
|
||||
@@ -12,6 +12,7 @@ interface DatabaseConfig {
|
||||
|
||||
val maxPoolSize: Int
|
||||
val connectionTimeoutMs: Long
|
||||
val statementTimeoutMs: Long
|
||||
|
||||
val jdbcConnectionUrl: String
|
||||
get() = "jdbc:postgresql://$host:$port/$name"
|
||||
|
||||
@@ -11,5 +11,6 @@ data class SerialDatabaseConfig(
|
||||
override val password: String? = null,
|
||||
override val passwordFile: String? = null,
|
||||
override val maxPoolSize: Int,
|
||||
override val connectionTimeoutMs: Long
|
||||
override val connectionTimeoutMs: Long,
|
||||
override val statementTimeoutMs: Long
|
||||
) : DatabaseConfig
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mtusi.messenger.main.config.redis
|
||||
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.config.getAs
|
||||
import org.koin.core.annotation.Provided
|
||||
import org.koin.core.annotation.Single
|
||||
|
||||
@Single
|
||||
class DefaultRedisConfig(
|
||||
@Provided app: Application
|
||||
) : RedisConfig by app.environment.config.property("redis").getAs<SerialRedisConfig>()
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.mtusi.messenger.main.config.redis
|
||||
|
||||
interface RedisConfig {
|
||||
|
||||
val host: String
|
||||
val port: Int
|
||||
|
||||
val username: String?
|
||||
val password: String?
|
||||
val passwordFile: String?
|
||||
|
||||
val connectTimeoutMs: Long
|
||||
val commandTimeoutMs: Long
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.mtusi.messenger.main.config.redis
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class SerialRedisConfig(
|
||||
override val host: String,
|
||||
override val port: Int,
|
||||
override val username: String? = null,
|
||||
override val password: String? = null,
|
||||
override val passwordFile: String? = null,
|
||||
override val connectTimeoutMs: Long,
|
||||
override val commandTimeoutMs: Long
|
||||
) : RedisConfig
|
||||
+1
-3
@@ -44,9 +44,7 @@ fun Routing.configureAuthenticationRouting() = route("/api/v1/auth/sessions") {
|
||||
authenticate(SESSION_AUTH) {
|
||||
delete("current") {
|
||||
|
||||
suspendedTransaction {
|
||||
authenticationService.revokeSession(call.currentUser.sessionId)
|
||||
}
|
||||
authenticationService.revokeSession(call.currentUser.session)
|
||||
|
||||
call.respond(HttpStatusCode.NoContent)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import kotlin.time.Instant
|
||||
data class Session(
|
||||
val id: UUID,
|
||||
val userId: UUID,
|
||||
val tokenHash: String,
|
||||
val createdAt: Instant,
|
||||
val expiresAt: Instant,
|
||||
)
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories._common
|
||||
|
||||
import com.mtusi.messenger.main.config.redis.RedisConfig
|
||||
import com.mtusi.messenger.main.utils.resolveSecret
|
||||
import io.lettuce.core.ClientOptions
|
||||
import io.lettuce.core.RedisClient
|
||||
import io.lettuce.core.RedisConnectionException
|
||||
import io.lettuce.core.RedisURI
|
||||
import io.lettuce.core.SocketOptions
|
||||
import io.lettuce.core.TimeoutOptions
|
||||
import io.lettuce.core.api.StatefulRedisConnection
|
||||
import io.lettuce.core.api.async.RedisAsyncCommands
|
||||
import io.lettuce.core.codec.StringCodec
|
||||
import kotlinx.coroutines.future.await
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import org.koin.core.annotation.Single
|
||||
import java.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
private val RECONNECT_BACKOFF = 1.seconds
|
||||
|
||||
/**
|
||||
* Lazily connected Redis client. The application must start and serve requests without Redis, so the connection
|
||||
* is opened on first use, a failed attempt is not retried for [RECONNECT_BACKOFF], and commands issued while
|
||||
* disconnected fail immediately instead of queueing behind the reconnect.
|
||||
*/
|
||||
@Single
|
||||
class RedisConnection(
|
||||
config: RedisConfig
|
||||
) : AutoCloseable {
|
||||
|
||||
private val uri = RedisURI.builder()
|
||||
.withHost(config.host)
|
||||
.withPort(config.port)
|
||||
.withTimeout(Duration.ofMillis(config.commandTimeoutMs))
|
||||
.apply {
|
||||
val password = resolveSecret(config.password, config.passwordFile)
|
||||
if (password != null) {
|
||||
if (config.username != null) withAuthentication(config.username, password) else withPassword(password.toCharArray())
|
||||
}
|
||||
}
|
||||
.build()
|
||||
|
||||
private val client = RedisClient.create().apply {
|
||||
options = ClientOptions.builder()
|
||||
.autoReconnect(true)
|
||||
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
|
||||
.timeoutOptions(TimeoutOptions.enabled(Duration.ofMillis(config.commandTimeoutMs)))
|
||||
.socketOptions(SocketOptions.builder().connectTimeout(Duration.ofMillis(config.connectTimeoutMs)).build())
|
||||
.build()
|
||||
}
|
||||
|
||||
private val mutex = Mutex()
|
||||
|
||||
@Volatile
|
||||
private var connection: StatefulRedisConnection<String, String>? = null
|
||||
|
||||
@Volatile
|
||||
private var nextAttempt = TimeSource.Monotonic.markNow()
|
||||
|
||||
suspend fun commands(): RedisAsyncCommands<String, String> {
|
||||
return (connection ?: connect()).async()
|
||||
}
|
||||
|
||||
private suspend fun connect(): StatefulRedisConnection<String, String> = mutex.withLock {
|
||||
|
||||
connection?.let { return it }
|
||||
|
||||
if (nextAttempt.hasNotPassedNow()) {
|
||||
throw RedisConnectionException("Redis is unavailable, next connection attempt is postponed")
|
||||
}
|
||||
|
||||
return try {
|
||||
client.connectAsync(StringCodec.UTF8, uri).await().also { connection = it }
|
||||
} catch (e: Exception) {
|
||||
nextAttempt = TimeSource.Monotonic.markNow() + RECONNECT_BACKOFF
|
||||
throw e as? RedisConnectionException ?: RedisConnectionException("Unable to connect to Redis", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
connection?.close()
|
||||
client.shutdown()
|
||||
}
|
||||
|
||||
}
|
||||
+9
-3
@@ -13,6 +13,7 @@ import org.jetbrains.exposed.v1.jdbc.selectAll
|
||||
import org.koin.core.annotation.Single
|
||||
import java.util.UUID
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Instant
|
||||
|
||||
@Single
|
||||
@@ -21,20 +22,24 @@ class ExposedSessionRepository : SessionRepository {
|
||||
override fun create(
|
||||
userId: UUID,
|
||||
tokenHash: String,
|
||||
expiresAt: Instant
|
||||
ttl: Duration
|
||||
): Session {
|
||||
|
||||
val createdAt = Clock.System.nowMicros()
|
||||
val expiresAt = createdAt + ttl
|
||||
|
||||
val insertedRow = SessionModel.insert {
|
||||
it[this.userId] = userId
|
||||
it[this.tokenHash] = tokenHash
|
||||
it[this.createdAt] = Clock.System.nowMicros()
|
||||
it[this.createdAt] = createdAt
|
||||
it[this.expiresAt] = expiresAt
|
||||
}
|
||||
|
||||
return Session(
|
||||
id = insertedRow[SessionModel.id].value,
|
||||
userId = userId,
|
||||
createdAt = insertedRow[SessionModel.createdAt],
|
||||
tokenHash = tokenHash,
|
||||
createdAt = createdAt,
|
||||
expiresAt = expiresAt
|
||||
)
|
||||
}
|
||||
@@ -60,6 +65,7 @@ class ExposedSessionRepository : SessionRepository {
|
||||
private fun ResultRow.toSession() = Session(
|
||||
id = this[SessionModel.id].value,
|
||||
userId = this[SessionModel.userId].value,
|
||||
tokenHash = this[SessionModel.tokenHash],
|
||||
createdAt = this[SessionModel.createdAt],
|
||||
expiresAt = this[SessionModel.expiresAt]
|
||||
)
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ package com.mtusi.messenger.main.infrastructure.repositories.authentication.sess
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.Repository
|
||||
import java.util.UUID
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Instant
|
||||
|
||||
interface SessionRepository : Repository<UUID, Session> {
|
||||
@@ -10,7 +11,7 @@ interface SessionRepository : Repository<UUID, Session> {
|
||||
fun create(
|
||||
userId: UUID,
|
||||
tokenHash: String,
|
||||
expiresAt: Instant
|
||||
ttl: Duration
|
||||
): Session
|
||||
|
||||
fun findActiveByTokenHash(
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
|
||||
sealed class CachedSession {
|
||||
|
||||
data class Active(val session: Session) : CachedSession()
|
||||
|
||||
data object Revoked : CachedSession()
|
||||
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
|
||||
|
||||
import com.mtusi.messenger.main.compat.serializers.SerialUUID
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
|
||||
import io.lettuce.core.SetArgs
|
||||
import kotlinx.coroutines.future.await
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.koin.core.annotation.Single
|
||||
import kotlin.time.Instant
|
||||
|
||||
private const val KEY_PREFIX = "session:"
|
||||
private const val REVOKED = "revoked"
|
||||
|
||||
@Single
|
||||
class RedisSessionCacheRepository(
|
||||
private val redis: RedisConnection
|
||||
) : SessionCacheRepository {
|
||||
|
||||
override suspend fun find(
|
||||
tokenHash: String
|
||||
): CachedSession? {
|
||||
|
||||
val value = redis.commands().get(key(tokenHash)).await() ?: return null
|
||||
|
||||
if (value == REVOKED) {
|
||||
return CachedSession.Revoked
|
||||
}
|
||||
|
||||
return CachedSession.Active(
|
||||
Json.decodeFromString<SessionEntry>(value).toSession(tokenHash)
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun putIfAbsent(
|
||||
session: Session,
|
||||
cachedUntil: Instant
|
||||
) {
|
||||
redis.commands().set(
|
||||
key(session.tokenHash),
|
||||
Json.encodeToString(SessionEntry.from(session)),
|
||||
SetArgs.Builder.nx().pxAt(cachedUntil.toEpochMilliseconds())
|
||||
).await()
|
||||
}
|
||||
|
||||
override suspend fun revoke(
|
||||
session: Session
|
||||
) {
|
||||
redis.commands().set(
|
||||
key(session.tokenHash),
|
||||
REVOKED,
|
||||
SetArgs.Builder.pxAt(session.expiresAt.toEpochMilliseconds())
|
||||
).await()
|
||||
}
|
||||
|
||||
private fun key(tokenHash: String) = KEY_PREFIX + tokenHash
|
||||
|
||||
@Serializable
|
||||
private data class SessionEntry(
|
||||
val id: SerialUUID,
|
||||
val userId: SerialUUID,
|
||||
val createdAt: Instant,
|
||||
val expiresAt: Instant
|
||||
) {
|
||||
|
||||
fun toSession(tokenHash: String) = Session(
|
||||
id = id,
|
||||
userId = userId,
|
||||
tokenHash = tokenHash,
|
||||
createdAt = createdAt,
|
||||
expiresAt = expiresAt
|
||||
)
|
||||
|
||||
companion object {
|
||||
fun from(session: Session) = SessionEntry(
|
||||
id = session.id,
|
||||
userId = session.userId,
|
||||
createdAt = session.createdAt,
|
||||
expiresAt = session.expiresAt
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.Repository
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* Cache-aside copy of [com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository].
|
||||
* PostgreSQL stays the source of truth: losing every key only costs a database lookup.
|
||||
*/
|
||||
interface SessionCacheRepository : Repository<String, Session> {
|
||||
|
||||
suspend fun find(
|
||||
tokenHash: String
|
||||
): CachedSession?
|
||||
|
||||
/**
|
||||
* Stores the session until [cachedUntil] unless the key already exists, so a lookup racing with a logout
|
||||
* cannot overwrite the tombstone written by [revoke].
|
||||
*/
|
||||
suspend fun putIfAbsent(
|
||||
session: Session,
|
||||
cachedUntil: Instant
|
||||
)
|
||||
|
||||
/**
|
||||
* Replaces the entry with a tombstone that lives until the session would have expired.
|
||||
*/
|
||||
suspend fun revoke(
|
||||
session: Session
|
||||
)
|
||||
|
||||
}
|
||||
+10
-3
@@ -16,12 +16,19 @@ interface AuthenticationService {
|
||||
userId: UUID
|
||||
): IssuedSession
|
||||
|
||||
fun findSessionByToken(
|
||||
/**
|
||||
* Opens its own transaction only on a cache miss, so it must not be called inside one.
|
||||
*/
|
||||
suspend fun findSessionByToken(
|
||||
token: String
|
||||
): Session?
|
||||
|
||||
fun revokeSession(
|
||||
sessionId: UUID
|
||||
/**
|
||||
* Deletes the session in PostgreSQL, then replaces its cached copy with a tombstone. Without Redis only the
|
||||
* database is updated: a copy cached before the outage can then live for at most the cache TTL.
|
||||
*/
|
||||
suspend fun revokeSession(
|
||||
session: Session
|
||||
): Boolean
|
||||
|
||||
}
|
||||
|
||||
+67
-10
@@ -5,16 +5,21 @@ import com.mtusi.messenger.main.infrastructure.dto.User
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.CachedSession
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache.SessionCacheRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository
|
||||
import com.mtusi.messenger.main.infrastructure.services.hashing.HashingService
|
||||
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
|
||||
import com.mtusi.messenger.main.plugins.suspendedTransaction
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import com.mtusi.messenger.main.utils.nowMicros
|
||||
import io.lettuce.core.RedisException
|
||||
import org.koin.core.annotation.Single
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import java.util.UUID
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
|
||||
private const val TOKEN_BYTES = 32
|
||||
@@ -23,10 +28,13 @@ private const val TOKEN_BYTES = 32
|
||||
class DefaultAuthenticationService(
|
||||
private val userRepository: UserRepository,
|
||||
private val sessionRepository: SessionRepository,
|
||||
private val sessionCacheRepository: SessionCacheRepository,
|
||||
private val hashingService: HashingService,
|
||||
private val config: AuthenticationConfig
|
||||
) : AuthenticationService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(DefaultAuthenticationService::class.java)
|
||||
|
||||
private val random = SecureRandom()
|
||||
|
||||
private val dummyPasswordHash by lazy {
|
||||
@@ -64,7 +72,7 @@ class DefaultAuthenticationService(
|
||||
val session = sessionRepository.create(
|
||||
userId = userId,
|
||||
tokenHash = token.toByteArray().computeSha256(),
|
||||
expiresAt = Clock.System.nowMicros() + config.sessionTtlSeconds.seconds
|
||||
ttl = config.sessionTtlSeconds.seconds
|
||||
)
|
||||
|
||||
return IssuedSession(
|
||||
@@ -73,19 +81,68 @@ class DefaultAuthenticationService(
|
||||
)
|
||||
}
|
||||
|
||||
override fun findSessionByToken(
|
||||
override suspend fun findSessionByToken(
|
||||
token: String
|
||||
): Session? {
|
||||
return sessionRepository.findActiveByTokenHash(
|
||||
tokenHash = token.toByteArray().computeSha256(),
|
||||
now = Clock.System.now()
|
||||
)
|
||||
|
||||
val tokenHash = token.toByteArray().computeSha256()
|
||||
val now = Clock.System.now()
|
||||
|
||||
when (val cached = findCachedSession(tokenHash)) {
|
||||
is CachedSession.Revoked -> return null
|
||||
is CachedSession.Active -> return cached.session.takeIf { it.expiresAt > now }
|
||||
null -> Unit
|
||||
}
|
||||
|
||||
val session = suspendedTransaction {
|
||||
sessionRepository.findActiveByTokenHash(tokenHash, now)
|
||||
} ?: return null
|
||||
|
||||
cacheSession(session, now)
|
||||
|
||||
return session
|
||||
}
|
||||
|
||||
override fun revokeSession(
|
||||
sessionId: UUID
|
||||
override suspend fun revokeSession(
|
||||
session: Session
|
||||
): Boolean {
|
||||
return sessionRepository.deleteById(sessionId)
|
||||
|
||||
val isDeleted = suspendedTransaction {
|
||||
sessionRepository.deleteById(session.id)
|
||||
}
|
||||
|
||||
try {
|
||||
sessionCacheRepository.revoke(session)
|
||||
} catch (e: RedisException) {
|
||||
logger.warn("Session cache is unavailable, revoked session is not tombstoned: ${e.message}")
|
||||
}
|
||||
|
||||
return isDeleted
|
||||
}
|
||||
|
||||
private suspend fun findCachedSession(
|
||||
tokenHash: String
|
||||
): CachedSession? {
|
||||
return try {
|
||||
sessionCacheRepository.find(tokenHash)
|
||||
} catch (e: RedisException) {
|
||||
logger.warn("Session cache is unavailable, reading from the database: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun cacheSession(
|
||||
session: Session,
|
||||
now: Instant
|
||||
) {
|
||||
try {
|
||||
sessionCacheRepository.putIfAbsent(
|
||||
session = session,
|
||||
cachedUntil = minOf(session.expiresAt, now + config.sessionCacheTtlSeconds.seconds)
|
||||
)
|
||||
} catch (e: RedisException) {
|
||||
logger.warn("Session cache is unavailable, session is not cached: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.message.MessageModel
|
||||
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
|
||||
import com.mtusi.messenger.main.utils.resolveSecret
|
||||
import com.typesafe.config.ConfigFactory
|
||||
import com.zaxxer.hikari.HikariConfig
|
||||
import com.zaxxer.hikari.HikariDataSource
|
||||
@@ -30,6 +31,7 @@ import javax.sql.DataSource
|
||||
|
||||
private const val MIGRATIONS_DIRECTORY = "src/main/resources/migrations"
|
||||
private const val DEVELOPMENT_DATABASE_CONFIG = "run/development/config/database.conf"
|
||||
private const val VALIDATION_TIMEOUT_MS = 1000L
|
||||
|
||||
fun Application.configureDatabase() {
|
||||
|
||||
@@ -57,19 +59,15 @@ private fun DatabaseConfig.createDataSource(): HikariDataSource {
|
||||
poolName = "messenger"
|
||||
jdbcUrl = jdbcConnectionUrl
|
||||
username = this@createDataSource.username
|
||||
password = resolvePassword()
|
||||
password = resolveSecret(this@createDataSource.password, passwordFile).orEmpty()
|
||||
maximumPoolSize = maxPoolSize
|
||||
connectionTimeout = connectionTimeoutMs
|
||||
validationTimeout = minOf(VALIDATION_TIMEOUT_MS, connectionTimeoutMs - 1)
|
||||
addDataSourceProperty("options", "-c statement_timeout=$statementTimeoutMs")
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
private fun DatabaseConfig.resolvePassword(): String {
|
||||
return password
|
||||
?: passwordFile?.let { File(it).readText().trim() }
|
||||
?: ""
|
||||
}
|
||||
|
||||
fun applyDatabaseMigrations(
|
||||
dataSource: DataSource
|
||||
) {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.ApplicationStopped
|
||||
import org.koin.ktor.ext.get
|
||||
|
||||
fun Application.configureRedis() {
|
||||
|
||||
val redisConnection = get<RedisConnection>()
|
||||
|
||||
monitor.subscribe(ApplicationStopped) {
|
||||
redisConnection.close()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -12,12 +12,16 @@ import io.ktor.server.plugins.BadRequestException
|
||||
import io.ktor.server.plugins.NotFoundException
|
||||
import io.ktor.server.plugins.UnsupportedMediaTypeException
|
||||
import io.ktor.server.plugins.statuspages.StatusPages
|
||||
import io.lettuce.core.RedisException
|
||||
import kotlinx.serialization.SerializationException
|
||||
import java.sql.SQLException
|
||||
import java.sql.SQLTransientConnectionException
|
||||
|
||||
private const val CONNECTION_ERROR_SQL_STATE_CLASS = "08"
|
||||
|
||||
// admin_shutdown, crash_shutdown, cannot_connect_now: the server is going down or still starting.
|
||||
private const val SERVER_SHUTDOWN_SQL_STATE_PREFIX = "57P"
|
||||
|
||||
fun Application.configureStatusPages() = install(StatusPages) {
|
||||
exception<ApiException> { call, cause ->
|
||||
call.respondError(cause.code, cause.message ?: cause.code.wire)
|
||||
@@ -46,6 +50,10 @@ fun Application.configureStatusPages() = install(StatusPages) {
|
||||
call.respondError(ErrorCode.INTERNAL_ERROR, "internal error")
|
||||
}
|
||||
}
|
||||
exception<RedisException> { call, cause ->
|
||||
call.application.log.warn("Redis unavailable: ${cause.message}")
|
||||
call.respondError(ErrorCode.UNAVAILABLE, "service temporarily unavailable")
|
||||
}
|
||||
exception<Throwable> { call, cause ->
|
||||
call.application.log.error("Unhandled error", cause)
|
||||
call.respondError(ErrorCode.INTERNAL_ERROR, "internal error")
|
||||
@@ -61,6 +69,10 @@ fun Application.configureStatusPages() = install(StatusPages) {
|
||||
private fun SQLException.isConnectionFailure(): Boolean {
|
||||
return generateSequence<Throwable>(this) { it.cause }.any {
|
||||
it is SQLTransientConnectionException ||
|
||||
(it is SQLException && it.sqlState?.startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) == true)
|
||||
(it is SQLException && it.sqlState.isUnavailableState())
|
||||
}
|
||||
}
|
||||
|
||||
private fun String?.isUnavailableState(): Boolean {
|
||||
return this != null && (startsWith(CONNECTION_ERROR_SQL_STATE_CLASS) || startsWith(SERVER_SHUTDOWN_SQL_STATE_PREFIX))
|
||||
}
|
||||
|
||||
@@ -32,14 +32,9 @@ fun Application.configureAuthentication() {
|
||||
|
||||
bearerSession(SESSION_AUTH) {
|
||||
authenticate { token ->
|
||||
val session = suspendedTransaction {
|
||||
authenticationService.findSessionByToken(token)
|
||||
} ?: return@authenticate null
|
||||
val session = authenticationService.findSessionByToken(token) ?: return@authenticate null
|
||||
|
||||
return@authenticate UserPrincipal(
|
||||
id = session.userId,
|
||||
sessionId = session.id
|
||||
)
|
||||
return@authenticate UserPrincipal(session)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
package com.mtusi.messenger.main.plugins.authentication
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import java.util.UUID
|
||||
|
||||
data class UserPrincipal(
|
||||
val id: UUID,
|
||||
val sessionId: UUID
|
||||
)
|
||||
val session: Session
|
||||
) {
|
||||
|
||||
val id: UUID
|
||||
get() = session.userId
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.mtusi.messenger.main.utils
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Secrets come either inline (local development) or as a mounted file (Docker secrets), the inline value wins.
|
||||
*/
|
||||
fun resolveSecret(
|
||||
value: String?,
|
||||
file: String?
|
||||
): String? {
|
||||
return value ?: file?.let { File(it).readText().trim() }
|
||||
}
|
||||
@@ -27,10 +27,23 @@ database {
|
||||
maxPoolSize = 10
|
||||
maxPoolSize = ${?DB_MAX_POOL_SIZE}
|
||||
connectionTimeoutMs = 2000
|
||||
statementTimeoutMs = 5000
|
||||
}
|
||||
|
||||
redis {
|
||||
host = "localhost"
|
||||
host = ${?REDIS_HOST}
|
||||
port = 6379
|
||||
port = ${?REDIS_PORT}
|
||||
password = ${?REDIS_PASSWORD}
|
||||
passwordFile = ${?REDIS_PASSWORD_FILE}
|
||||
connectTimeoutMs = 500
|
||||
commandTimeoutMs = 500
|
||||
}
|
||||
|
||||
authentication {
|
||||
realm = "messenger"
|
||||
sessionTtlSeconds = 3600
|
||||
sessionTtlSeconds = ${?SESSION_TTL_SECONDS}
|
||||
sessionCacheTtlSeconds = 60
|
||||
}
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
|
||||
|
||||
import com.mtusi.messenger.main.config.redis.SerialRedisConfig
|
||||
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
|
||||
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.utils.nowMicros
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import java.util.UUID
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
|
||||
class RedisSessionCacheRepositoryTest {
|
||||
|
||||
private fun withRepository(block: suspend (RedisSessionCacheRepository) -> Unit) = runTest {
|
||||
val endpoint = TestRedis.endpoint()
|
||||
val connection = RedisConnection(
|
||||
SerialRedisConfig(
|
||||
host = endpoint.host,
|
||||
port = endpoint.port,
|
||||
password = TestRedis.PASSWORD,
|
||||
connectTimeoutMs = 2000,
|
||||
commandTimeoutMs = 2000
|
||||
)
|
||||
)
|
||||
connection.use { block(RedisSessionCacheRepository(it)) }
|
||||
}
|
||||
|
||||
private fun session(ttl: Duration = 10.minutes): Session {
|
||||
val now = Clock.System.nowMicros()
|
||||
return Session(
|
||||
id = UUID.randomUUID(),
|
||||
userId = UUID.randomUUID(),
|
||||
tokenHash = UUID.randomUUID().toString().replace("-", ""),
|
||||
createdAt = now,
|
||||
expiresAt = now + ttl
|
||||
)
|
||||
}
|
||||
|
||||
private fun ttlSeconds(session: Session): Long {
|
||||
return TestRedis.cli(TestRedis.container, "TTL", "session:${session.tokenHash}").toLong()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cached session round-trips and expires together with the session`() = withRepository { repository ->
|
||||
val session = session()
|
||||
|
||||
assertNull(repository.find(session.tokenHash))
|
||||
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
assertEquals(CachedSession.Active(session), repository.find(session.tokenHash))
|
||||
assertTrue(ttlSeconds(session) in 590..600, "key must expire at cachedUntil")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `revoke replaces a cached session with a tombstone`() = withRepository { repository ->
|
||||
val session = session()
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
repository.revoke(session)
|
||||
|
||||
assertEquals(CachedSession.Revoked, repository.find(session.tokenHash))
|
||||
assertTrue(ttlSeconds(session) in 590..600, "tombstone must live until the session would expire")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `late cache fill cannot overwrite a tombstone`() = withRepository { repository ->
|
||||
val session = session()
|
||||
|
||||
// A lookup read the session from PostgreSQL before logout and stores it after the logout finished.
|
||||
repository.revoke(session)
|
||||
repository.putIfAbsent(session, cachedUntil = session.expiresAt)
|
||||
|
||||
assertEquals(CachedSession.Revoked, repository.find(session.tokenHash))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.extensions.ErrorBody
|
||||
import com.mtusi.messenger.main.support.TestDatabase
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.support.auth
|
||||
import com.mtusi.messenger.main.support.createChat
|
||||
import com.mtusi.messenger.main.support.register
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.basicAuth
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.statement.HttpResponse
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.TimeSource
|
||||
|
||||
class DependencyFailureTest {
|
||||
|
||||
/**
|
||||
* An unknown token can only be checked against PostgreSQL, so without it the answer is 503, never a success.
|
||||
*/
|
||||
private suspend fun HttpClient.assertAnonymousRejected(
|
||||
unknownTokenStatus: HttpStatusCode = HttpStatusCode.Unauthorized
|
||||
) {
|
||||
assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me").status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, get("/api/v1/users/me") { header("X-User-Id", "1") }.status)
|
||||
assertEquals(
|
||||
unknownTokenStatus,
|
||||
get("/api/v1/users/me") { header("Authorization", "Bearer never-issued-token") }.status
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun assertUnavailable(response: HttpResponse) {
|
||||
assertEquals(HttpStatusCode.ServiceUnavailable, response.status)
|
||||
assertEquals("unavailable", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without Redis requests bypass the cache`() = runApp(
|
||||
redis = TestRedis.unreachableEndpoint()
|
||||
) { client ->
|
||||
assertEquals(HttpStatusCode.OK, client.get("/health/ready").status)
|
||||
|
||||
val alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
client.createChat(alice, "no redis", listOf(alice.id, bob.id))
|
||||
|
||||
client.assertAnonymousRejected()
|
||||
|
||||
// PostgreSQL is the source of truth: logout still works and is visible immediately.
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hanging Redis costs one command timeout and recovers`() {
|
||||
val redis = TestRedis.create().also { it.start() }
|
||||
val docker = redis.dockerClient
|
||||
|
||||
try {
|
||||
runApp(redis = TestRedis.endpoint(redis)) { client ->
|
||||
val alice = client.register("alice")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
docker.pauseContainerCmd(redis.containerId).exec()
|
||||
|
||||
val started = TimeSource.Monotonic.markNow()
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertTrue(started.elapsedNow() < 2.seconds, "cache lookup must be bounded by the command timeout")
|
||||
|
||||
client.assertAnonymousRejected()
|
||||
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
docker.unpauseContainerCmd(redis.containerId).exec()
|
||||
|
||||
// The copy cached before the pause is replaced by the delayed tombstone, not resurrected.
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
val bob = client.register("bob")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(bob) }.status)
|
||||
assertTrue(
|
||||
TestRedis.cli(redis, "EXISTS", "session:${bob.token.toByteArray().computeSha256()}") == "1",
|
||||
"cache is used again after recovery"
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
redis.stop()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `without PostgreSQL requests fail with a bounded 503`() {
|
||||
val database = TestDatabase.create().also { it.start() }
|
||||
|
||||
try {
|
||||
runApp(database = database, databaseConnectionTimeoutMs = 2000) { client ->
|
||||
val alice = client.register("alice")
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
database.dockerClient.stopContainerCmd(database.containerId).exec()
|
||||
|
||||
val started = TimeSource.Monotonic.markNow()
|
||||
|
||||
// The session itself is still served from Redis, the user lookup needs PostgreSQL.
|
||||
assertUnavailable(client.get("/api/v1/users/me") { auth(alice) })
|
||||
assertUnavailable(client.post("/api/v1/auth/sessions") { basicAuth(alice.user.username, alice.password) })
|
||||
assertEquals(HttpStatusCode.ServiceUnavailable, client.get("/health/ready").status)
|
||||
assertEquals(HttpStatusCode.OK, client.get("/health/live").status)
|
||||
|
||||
assertTrue(started.elapsedNow() < 15.seconds, "every request must fail within the pool timeout")
|
||||
|
||||
client.assertAnonymousRejected(unknownTokenStatus = HttpStatusCode.ServiceUnavailable)
|
||||
}
|
||||
} finally {
|
||||
database.stop()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.support.TestRedis
|
||||
import com.mtusi.messenger.main.support.TestUser
|
||||
import com.mtusi.messenger.main.support.auth
|
||||
import com.mtusi.messenger.main.support.register
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import com.mtusi.messenger.main.utils.computeSha256
|
||||
import io.ktor.client.request.delete
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class SessionCacheTest {
|
||||
|
||||
private val redis = TestRedis.container
|
||||
|
||||
private fun cached(user: TestUser): String {
|
||||
return TestRedis.cli(redis, "GET", "session:${user.token.toByteArray().computeSha256()}")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `first authenticated request fills the cache`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
|
||||
assertEquals("", cached(alice), "login does not write to the cache")
|
||||
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
|
||||
assertTrue(cached(alice).contains(alice.id.toString()))
|
||||
|
||||
// The session lives for an hour, its cached copy at most sessionCacheTtlSeconds.
|
||||
val ttl = TestRedis.cli(redis, "TTL", "session:${alice.token.toByteArray().computeSha256()}").toLong()
|
||||
assertTrue(ttl in 1..60, "cached copy TTL was $ttl")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `logout leaves a tombstone and the token is rejected`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
client.get("/api/v1/users/me") { auth(alice) }
|
||||
|
||||
assertEquals(HttpStatusCode.NoContent, client.delete("/api/v1/auth/sessions/current") { auth(alice) }.status)
|
||||
|
||||
assertEquals("revoked", cached(alice))
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `emptied cache falls back to PostgreSQL`() = runApp { client ->
|
||||
val alice = client.register("alice")
|
||||
val bob = client.register("bob")
|
||||
client.get("/api/v1/users/me") { auth(alice) }
|
||||
client.delete("/api/v1/auth/sessions/current") { auth(bob) }
|
||||
|
||||
TestRedis.cli(redis, "FLUSHALL")
|
||||
|
||||
// PostgreSQL is the source of truth: the live session survives, the revoked one stays revoked.
|
||||
assertEquals(HttpStatusCode.OK, client.get("/api/v1/users/me") { auth(alice) }.status)
|
||||
assertEquals(HttpStatusCode.Unauthorized, client.get("/api/v1/users/me") { auth(bob) }.status)
|
||||
assertTrue(cached(alice).contains(alice.id.toString()), "cache is filled again")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import io.ktor.server.testing.testApplication
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonNamingStrategy
|
||||
import org.testcontainers.containers.PostgreSQLContainer
|
||||
import java.util.UUID
|
||||
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
@@ -45,28 +46,51 @@ data class TestUser(
|
||||
get() = user.id
|
||||
}
|
||||
|
||||
private fun testConfig(sessionTtlSeconds: Long) = HoconApplicationConfig(
|
||||
data class RedisEndpoint(
|
||||
val host: String,
|
||||
val port: Int,
|
||||
)
|
||||
|
||||
private fun testConfig(
|
||||
sessionTtlSeconds: Long,
|
||||
database: PostgreSQLContainer<*>,
|
||||
databaseConnectionTimeoutMs: Long,
|
||||
redis: RedisEndpoint,
|
||||
) = HoconApplicationConfig(
|
||||
ConfigFactory.parseMap(
|
||||
mapOf(
|
||||
"database.host" to TestDatabase.container.host,
|
||||
"database.port" to TestDatabase.container.firstMappedPort,
|
||||
"database.name" to TestDatabase.NAME,
|
||||
"database.username" to TestDatabase.USERNAME,
|
||||
"database.password" to TestDatabase.PASSWORD,
|
||||
"database.host" to database.host,
|
||||
"database.port" to database.firstMappedPort,
|
||||
"database.name" to database.databaseName,
|
||||
"database.username" to database.username,
|
||||
"database.password" to database.password,
|
||||
"database.maxPoolSize" to 10,
|
||||
"database.connectionTimeoutMs" to 10000,
|
||||
"database.connectionTimeoutMs" to databaseConnectionTimeoutMs,
|
||||
"database.statementTimeoutMs" to 5000,
|
||||
"redis.host" to redis.host,
|
||||
"redis.port" to redis.port,
|
||||
"redis.password" to TestRedis.PASSWORD,
|
||||
"redis.connectTimeoutMs" to 500,
|
||||
"redis.commandTimeoutMs" to 500,
|
||||
"authentication.realm" to "messenger",
|
||||
"authentication.sessionTtlSeconds" to sessionTtlSeconds,
|
||||
"authentication.sessionCacheTtlSeconds" to 60,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
* Docker Desktop can be slow to accept the first connection, hence the generous default database timeout.
|
||||
*/
|
||||
fun runApp(
|
||||
sessionTtlSeconds: Long = 3600,
|
||||
database: PostgreSQLContainer<*> = TestDatabase.container,
|
||||
databaseConnectionTimeoutMs: Long = 10000,
|
||||
redis: RedisEndpoint = TestRedis.endpoint(),
|
||||
block: suspend ApplicationTestBuilder.(HttpClient) -> Unit
|
||||
) = testApplication {
|
||||
environment {
|
||||
config = testConfig(sessionTtlSeconds)
|
||||
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis)
|
||||
}
|
||||
application {
|
||||
module()
|
||||
|
||||
@@ -14,11 +14,17 @@ object TestDatabase {
|
||||
const val PASSWORD = "messenger"
|
||||
|
||||
val container: PostgreSQLContainer<*> by lazy {
|
||||
PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres"))
|
||||
create().also { it.start() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A separate, not yet started container for tests that stop the database.
|
||||
*/
|
||||
fun create(): PostgreSQLContainer<*> {
|
||||
return PostgreSQLContainer(DockerImageName.parse("postgres:17.6-alpine3.22").asCompatibleSubstituteFor("postgres"))
|
||||
.withDatabaseName(NAME)
|
||||
.withUsername(USERNAME)
|
||||
.withPassword(PASSWORD)
|
||||
.also { it.start() }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.mtusi.messenger.main.support
|
||||
|
||||
import org.testcontainers.containers.GenericContainer
|
||||
import org.testcontainers.utility.DockerImageName
|
||||
import java.net.ServerSocket
|
||||
|
||||
/**
|
||||
* One Redis container per test JVM, same image and memory settings as compose.yaml.
|
||||
*/
|
||||
object TestRedis {
|
||||
|
||||
const val PASSWORD = "messenger"
|
||||
|
||||
private const val PORT = 6379
|
||||
|
||||
val container: GenericContainer<*> by lazy {
|
||||
create().also { it.start() }
|
||||
}
|
||||
|
||||
/**
|
||||
* A separate, not yet started container for tests that pause or flush Redis.
|
||||
*/
|
||||
fun create(): GenericContainer<*> {
|
||||
return GenericContainer(DockerImageName.parse("redis:8.4.0-alpine"))
|
||||
.withExposedPorts(PORT)
|
||||
.withCommand(
|
||||
"redis-server",
|
||||
"--requirepass", PASSWORD,
|
||||
"--save", "",
|
||||
"--appendonly", "no",
|
||||
"--maxmemory-policy", "volatile-lru"
|
||||
)
|
||||
}
|
||||
|
||||
fun endpoint(container: GenericContainer<*> = this.container) = RedisEndpoint(
|
||||
host = container.host,
|
||||
port = container.getMappedPort(PORT)
|
||||
)
|
||||
|
||||
/**
|
||||
* An endpoint nobody listens on: connections are refused immediately.
|
||||
*/
|
||||
fun unreachableEndpoint(): RedisEndpoint {
|
||||
val port = ServerSocket(0).use { it.localPort }
|
||||
return RedisEndpoint(host = "127.0.0.1", port = port)
|
||||
}
|
||||
|
||||
fun cli(container: GenericContainer<*>, vararg command: String): String {
|
||||
val result = container.execInContainer("redis-cli", "--no-auth-warning", "-a", PASSWORD, *command)
|
||||
check(result.exitCode == 0) { "redis-cli failed: ${result.stderr}" }
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user