Completed for a grade of five

This commit is contained in:
2026-10-09 11:50:01 +03:00
parent 1632fe4b16
commit dc5abb6fff
142 changed files with 8207 additions and 57 deletions
@@ -5,5 +5,6 @@ interface AuthenticationConfig {
val realm: String
val sessionTtlSeconds: Long
val sessionCacheTtlSeconds: Long
val sessionCacheSingleFlight: Boolean
}
@@ -6,5 +6,6 @@ import kotlinx.serialization.Serializable
data class SerialAuthenticationConfig(
override val realm: String,
override val sessionTtlSeconds: Long,
override val sessionCacheTtlSeconds: Long
override val sessionCacheTtlSeconds: Long,
override val sessionCacheSingleFlight: Boolean = true
) : AuthenticationConfig
@@ -13,11 +13,17 @@ import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlg
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.computeSha256
import io.lettuce.core.RedisException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import org.koin.core.annotation.Single
import org.slf4j.LoggerFactory
import java.io.IOException
import java.security.SecureRandom
import java.util.Base64
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.time.Clock
import kotlin.time.Instant
import kotlin.time.Duration.Companion.seconds
@@ -37,6 +43,17 @@ class DefaultAuthenticationService(
private val random = SecureRandom()
/**
* Database lookups currently running per token hash. Concurrent cache misses for one token wait for the
* lookup already in flight instead of each sending their own query (cache stampede protection).
*/
private val inFlightLookups = ConcurrentHashMap<String, CompletableDeferred<Session?>>()
/**
* Only availability changes are logged: with Redis down every request would otherwise add a warning.
*/
private val isCacheAvailable = AtomicBoolean(true)
private val dummyPasswordHash by lazy {
hashingService.computeHash(HashingAlgorithm.Argon2id, "dummy-password-for-timing")
}
@@ -94,13 +111,44 @@ class DefaultAuthenticationService(
null -> Unit
}
val session = suspendedTransaction {
if (!config.sessionCacheSingleFlight) {
return selectSession(tokenHash, now)?.also { cacheSession(it, now) }
}
val flight = CompletableDeferred<Session?>()
inFlightLookups.putIfAbsent(tokenHash, flight)?.let { leader ->
return leader.await()
}
try {
// The query is shared with the followers, so the leader's own cancellation must not abort it.
val session = withContext(NonCancellable) {
selectSession(tokenHash, now)
}
flight.complete(session)
// Requests arriving until the cache write lands reuse this result instead of starting a new lookup.
// A logout drops the flight first (see revokeSession), so a revoked session is never handed out here.
session?.let { cacheSession(it, now) }
return session
} catch (e: Throwable) {
flight.completeExceptionally(e)
throw e
} finally {
inFlightLookups.remove(tokenHash, flight)
}
}
private suspend fun selectSession(
tokenHash: String,
now: Instant
): Session? {
return suspendedTransaction {
sessionRepository.findActiveByTokenHash(tokenHash, now)
} ?: return null
cacheSession(session, now)
return session
}
}
override suspend fun revokeSession(
@@ -111,11 +159,10 @@ class DefaultAuthenticationService(
sessionRepository.deleteById(session.id)
}
try {
sessionCacheRepository.revoke(session)
} catch (e: RedisException) {
logger.warn("Session cache is unavailable, revoked session is not tombstoned: ${e.message}")
}
// A lookup that started before the delete must not be joined by requests arriving after the logout.
inFlightLookups.remove(session.tokenHash)
withCache { sessionCacheRepository.revoke(session) }
return isDeleted
}
@@ -123,26 +170,49 @@ class DefaultAuthenticationService(
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
}
return withCache { sessionCacheRepository.find(tokenHash) }
}
private suspend fun cacheSession(
session: Session,
now: Instant
) {
try {
withCache {
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}")
}
}
/**
* Runs a cache operation, treating an unavailable Redis as a miss: the database stays the source of truth.
* A command already written when Redis drops the connection fails with the raw [IOException] (connection
* reset), not with a [RedisException]; it means the same.
*/
private suspend fun <T> withCache(
operation: suspend () -> T
): T? {
return try {
operation().also {
if (isCacheAvailable.compareAndSet(false, true)) {
logger.info("Session cache is available again")
}
}
} catch (e: RedisException) {
onCacheUnavailable(e)
} catch (e: IOException) {
onCacheUnavailable(e)
}
}
private fun onCacheUnavailable(
cause: Exception
): Nothing? {
if (isCacheAvailable.compareAndSet(true, false)) {
logger.warn("Session cache is unavailable, sessions are read from the database: ${cause.message}")
}
return null
}
}
+3
View File
@@ -46,4 +46,7 @@ authentication {
sessionTtlSeconds = 3600
sessionTtlSeconds = ${?SESSION_TTL_SECONDS}
sessionCacheTtlSeconds = 60
# Collapse concurrent cache misses for one token into a single database lookup (track 1 compares on/off).
sessionCacheSingleFlight = true
sessionCacheSingleFlight = ${?SESSION_CACHE_SINGLE_FLIGHT}
}
@@ -85,7 +85,7 @@ class ChatControllerTest {
}
@Test
fun `failed chat creation leaves no partial rows`() = runApp { client ->
fun `unknown member is rejected before anything is written`() = runApp { client ->
val alice = client.register("alice")
val title = "atomic-${UUID.randomUUID()}"
@@ -0,0 +1,62 @@
package com.mtusi.messenger.main.infrastructure.repositories.chat
import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.exceptions.ExposedSQLException
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
import java.util.UUID
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
private const val FOREIGN_KEY_VIOLATION = "23503"
/**
* The service validates members before writing, so the rollback is exercised here directly: the chat row is
* inserted, the membership batch then fails on the foreign key, and the whole transaction must disappear.
*/
class ExposedChatRepositoryTest {
private val repository = ExposedChatRepository()
@Test
fun `chat row is rolled back when inserting members fails`() = runApp { client ->
val alice = client.register("alice")
val title = "rollback-${UUID.randomUUID()}"
val error = assertFailsWith<ExposedSQLException> {
transaction {
repository.create(title = title, memberIds = listOf(alice.id, UUID.randomUUID()))
}
}
assertEquals(FOREIGN_KEY_VIOLATION, error.sqlState)
val (chats, memberships) = transaction {
val chats = ChatModel.selectAll().where(ChatModel.title eq title).count()
val memberships = ChatMemberModel.selectAll().where(ChatMemberModel.userId eq alice.id).count()
chats to memberships
}
assertEquals(0, chats)
assertEquals(0, memberships)
}
@Test
fun `successful creation commits the chat and every member`() = runApp { client ->
val alice = client.register("alice")
val bob = client.register("bob")
val chat = transaction {
repository.create(title = "committed", memberIds = listOf(alice.id, bob.id))
}
val memberships = transaction {
ChatMemberModel.selectAll().where(ChatMemberModel.chatId eq chat.id).count()
}
assertEquals(2, memberships)
}
}
@@ -0,0 +1,159 @@
package com.mtusi.messenger.main.infrastructure.services.authentication
import com.mtusi.messenger.main.config.authentication.SerialAuthenticationConfig
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.ExposedUserRepository
import com.mtusi.messenger.main.infrastructure.services.hashing.DefaultHashingService
import com.mtusi.messenger.main.support.TestDatabase
import com.mtusi.messenger.main.utils.computeSha256
import com.mtusi.messenger.main.utils.nowMicros
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.jetbrains.exposed.v1.jdbc.Database
import java.util.UUID
import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.hours
import kotlin.time.Instant
private const val CONCURRENT_REQUESTS = 50
private const val SLOW_QUERY_MS = 200L
/**
* Cold cache and a deliberately slow lookup, so every request is guaranteed to overlap with the first one.
*/
class SessionLookupSingleFlightTest {
private val token = "token-${UUID.randomUUID()}"
private val tokenHash = token.toByteArray().computeSha256()
private val session = Clock.System.nowMicros().let {
Session(
id = UUID.randomUUID(),
userId = UUID.randomUUID(),
tokenHash = tokenHash,
createdAt = it,
expiresAt = it + 1.hours
)
}
private class CountingSessionRepository(private val session: Session) : SessionRepository {
val lookups = AtomicInteger()
override fun findActiveByTokenHash(tokenHash: String, now: Instant): Session? {
lookups.incrementAndGet()
Thread.sleep(SLOW_QUERY_MS)
return session.takeIf { it.tokenHash == tokenHash }
}
override fun create(userId: UUID, tokenHash: String, ttl: Duration) = error("not used")
override fun deleteById(id: UUID) = true
}
private class ColdCache : SessionCacheRepository {
val writes = AtomicInteger()
override suspend fun find(tokenHash: String): CachedSession? = null
override suspend fun putIfAbsent(session: Session, cachedUntil: Instant) {
writes.incrementAndGet()
}
override suspend fun revoke(session: Session) = Unit
}
@BeforeTest
fun connect() {
// The fakes do not touch the database, but the service still opens a transaction around the lookup.
TestDatabase.container.let { Database.connect(it.jdbcUrl, user = it.username, password = it.password) }
}
private fun service(singleFlight: Boolean, repository: SessionRepository, cache: SessionCacheRepository) =
DefaultAuthenticationService(
userRepository = ExposedUserRepository(),
sessionRepository = repository,
sessionCacheRepository = cache,
hashingService = DefaultHashingService(),
config = SerialAuthenticationConfig(
realm = "messenger",
sessionTtlSeconds = 3600,
sessionCacheTtlSeconds = 60,
sessionCacheSingleFlight = singleFlight
)
)
private fun stampede(service: AuthenticationService): List<Session?> = runBlocking(Dispatchers.Default) {
(0 until CONCURRENT_REQUESTS).map {
async { service.findSessionByToken(token) }
}.awaitAll()
}
@Test
fun `without single-flight every concurrent miss queries the database`() {
val repository = CountingSessionRepository(session)
val cache = ColdCache()
val results = stampede(service(singleFlight = false, repository, cache))
assertTrue(results.all { it == session })
assertEquals(CONCURRENT_REQUESTS, repository.lookups.get())
assertEquals(CONCURRENT_REQUESTS, cache.writes.get())
}
@Test
fun `with single-flight concurrent misses share one database lookup`() {
val repository = CountingSessionRepository(session)
val cache = ColdCache()
val results = stampede(service(singleFlight = true, repository, cache))
assertTrue(results.all { it == session })
assertEquals(1, repository.lookups.get())
assertEquals(1, cache.writes.get())
}
@Test
fun `request arriving after logout does not join a lookup started before it`() = runBlocking(Dispatchers.Default) {
val repository = CountingSessionRepository(session)
val service = service(singleFlight = true, repository, ColdCache())
// The leader's query is still running (SLOW_QUERY_MS) when the logout completes.
val leader = async { service.findSessionByToken(token) }
delay(SLOW_QUERY_MS / 4)
service.revokeSession(session)
val afterLogout = async { service.findSessionByToken(token) }
leader.await()
afterLogout.await()
assertEquals(2, repository.lookups.get(), "the request after logout must run its own lookup")
}
@Test
fun `lookup that finished before a request arrived is not reused`() = runBlocking {
val repository = CountingSessionRepository(session)
val service = service(singleFlight = true, repository, ColdCache())
service.findSessionByToken(token)
service.findSessionByToken(token)
assertEquals(2, repository.lookups.get())
}
}