forked from mtusi2026/mtusi2026lab2
Completed for a grade of five
This commit is contained in:
+1
-1
@@ -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()}"
|
||||
|
||||
|
||||
+62
@@ -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)
|
||||
}
|
||||
|
||||
}
|
||||
+159
@@ -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())
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user