forked from mtusi2026/mtusi2026lab2
Completed for a grade of five
This commit is contained in:
@@ -5,5 +5,6 @@ interface AuthenticationConfig {
|
||||
val realm: String
|
||||
val sessionTtlSeconds: Long
|
||||
val sessionCacheTtlSeconds: Long
|
||||
val sessionCacheSingleFlight: Boolean
|
||||
|
||||
}
|
||||
|
||||
+2
-1
@@ -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
|
||||
|
||||
+90
-20
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user