forked from mtusi2026/mtusi2026lab2
Move lab1 to lab2
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package com.mtusi.messenger.main
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.chat.InMemoryChatRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.message.InMemoryMessageRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.user.InMemoryUserRepository
|
||||
import com.mtusi.messenger.main.infrastructure.services.chat.DefaultChatService
|
||||
import com.mtusi.messenger.main.infrastructure.services.message.DefaultMessageService
|
||||
import com.mtusi.messenger.main.infrastructure.services.user.DefaultUserService
|
||||
import com.mtusi.messenger.main.plugins.Dependencies
|
||||
import com.mtusi.messenger.main.plugins.configureCallLogging
|
||||
import com.mtusi.messenger.main.plugins.configureContentNegotiation
|
||||
import com.mtusi.messenger.main.plugins.configureDefaultHeaders
|
||||
import com.mtusi.messenger.main.plugins.configureRequestId
|
||||
import com.mtusi.messenger.main.plugins.configureRouting
|
||||
import com.mtusi.messenger.main.plugins.configureStatusPages
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.netty.EngineMain
|
||||
|
||||
fun main(args: Array<String>): Unit = EngineMain.main(args)
|
||||
|
||||
fun Application.module() {
|
||||
val userRepository = InMemoryUserRepository()
|
||||
val chatRepository = InMemoryChatRepository()
|
||||
val messageRepository = InMemoryMessageRepository()
|
||||
|
||||
val userService = DefaultUserService(userRepository)
|
||||
val chatService = DefaultChatService(chatRepository, userRepository)
|
||||
val messageService = DefaultMessageService(chatRepository, messageRepository)
|
||||
|
||||
val dependencies = Dependencies(
|
||||
userService = userService,
|
||||
chatService = chatService,
|
||||
messageService = messageService,
|
||||
)
|
||||
|
||||
configureContentNegotiation()
|
||||
configureDefaultHeaders()
|
||||
configureRequestId()
|
||||
configureCallLogging()
|
||||
configureStatusPages()
|
||||
configureRouting(dependencies)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.mtusi.messenger.main.extensions
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.User
|
||||
import com.mtusi.messenger.main.infrastructure.services.user.UserService
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.plugins.RequestIdKey
|
||||
import io.ktor.server.application.ApplicationCall
|
||||
import io.ktor.server.response.header
|
||||
import io.ktor.server.response.respond
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ErrorBody(val error: ErrorDetails)
|
||||
|
||||
@Serializable
|
||||
data class ErrorDetails(
|
||||
val code: String,
|
||||
val message: String,
|
||||
val requestId: String,
|
||||
)
|
||||
|
||||
suspend fun ApplicationCall.respondError(code: ErrorCode, message: String) {
|
||||
val requestId = attributes[RequestIdKey]
|
||||
if (code == ErrorCode.UNAUTHORIZED) {
|
||||
response.header("WWW-Authenticate", "Basic realm=\"messenger\", charset=\"UTF-8\"")
|
||||
}
|
||||
respond(code.status, ErrorBody(ErrorDetails(code.wire, message, requestId)))
|
||||
}
|
||||
|
||||
private val UUID_REGEX = Regex(
|
||||
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
|
||||
)
|
||||
|
||||
fun isValidUuid(value: String): Boolean = UUID_REGEX.matches(value)
|
||||
|
||||
fun ApplicationCall.requireCurrentUser(userService: UserService): User {
|
||||
val header = request.headers["X-User-Id"]?.trim()
|
||||
if (header.isNullOrEmpty() || !isValidUuid(header)) {
|
||||
throw ApiException(ErrorCode.UNAUTHORIZED, "missing or invalid X-User-Id")
|
||||
}
|
||||
return userService.findById(header)
|
||||
?: throw ApiException(ErrorCode.UNAUTHORIZED, "unknown user")
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.chat
|
||||
|
||||
import com.mtusi.messenger.main.extensions.requireCurrentUser
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.chat.responses.ChatPageResponse
|
||||
import com.mtusi.messenger.main.infrastructure.services.chat.ChatService
|
||||
import com.mtusi.messenger.main.infrastructure.services.user.UserService
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.utils.requireNonBlankBounded
|
||||
import com.mtusi.messenger.main.utils.requireUuid
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.post
|
||||
import io.ktor.server.routing.route
|
||||
|
||||
private const val TITLE_MAX = 100
|
||||
|
||||
fun Routing.configureChatRouting(
|
||||
chatService: ChatService,
|
||||
userService: UserService,
|
||||
) = route("/api/v1/chats") {
|
||||
|
||||
post {
|
||||
|
||||
val actor = call.requireCurrentUser(userService)
|
||||
val body = call.receive<CreateChatRequest>()
|
||||
|
||||
requireNonBlankBounded(
|
||||
body.title,
|
||||
min = 1,
|
||||
max = TITLE_MAX,
|
||||
field = "title"
|
||||
)
|
||||
|
||||
val chat = chatService.create(actor.id, body.title, body.memberIds)
|
||||
call.respond(HttpStatusCode.Created, chat)
|
||||
}
|
||||
|
||||
get {
|
||||
|
||||
val actor = call.requireCurrentUser(userService)
|
||||
|
||||
val page = chatService.findPageAccessible(
|
||||
userId = actor.id,
|
||||
rawLimit = call.request.queryParameters["limit"],
|
||||
rawCursor = call.request.queryParameters["cursor"],
|
||||
)
|
||||
|
||||
call.respond(HttpStatusCode.OK, ChatPageResponse(page.items, page.nextCursor))
|
||||
}
|
||||
|
||||
get("{chat_id}") {
|
||||
|
||||
val actor = call.requireCurrentUser(userService)
|
||||
val chatId = call.parameters["chat_id"]
|
||||
?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id")
|
||||
|
||||
requireUuid(chatId, "chat_id")
|
||||
|
||||
val chat = chatService.findAccessible(actor.id, chatId)
|
||||
call.respond(HttpStatusCode.OK, chat)
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.chat.requests
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CreateChatRequest(
|
||||
val title: String,
|
||||
val memberIds: List<String>,
|
||||
)
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.chat.responses
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ChatPageResponse(
|
||||
val items: List<Chat>,
|
||||
val nextCursor: String?,
|
||||
)
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.health
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.health.responses.HealthResponse
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.route
|
||||
|
||||
fun Routing.configureHealthRouting() = route("/health") {
|
||||
|
||||
get("live") {
|
||||
call.respond(HttpStatusCode.OK, HealthResponse())
|
||||
}
|
||||
|
||||
get("ready") {
|
||||
call.respond(HttpStatusCode.OK, HealthResponse())
|
||||
}
|
||||
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.health.responses
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class HealthResponse(val status: String = "ok")
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.message
|
||||
|
||||
import com.mtusi.messenger.main.extensions.requireCurrentUser
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse
|
||||
import com.mtusi.messenger.main.infrastructure.services.message.MessageService
|
||||
import com.mtusi.messenger.main.infrastructure.services.user.UserService
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.utils.requireNonBlankBounded
|
||||
import com.mtusi.messenger.main.utils.requireUuid
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.post
|
||||
import io.ktor.server.routing.route
|
||||
|
||||
private const val TEXT_MAX = 4000
|
||||
|
||||
fun Routing.configureMessageRouting(
|
||||
messageService: MessageService,
|
||||
userService: UserService,
|
||||
) = route("/api/v1/chats/{chat_id}/messages") {
|
||||
|
||||
post {
|
||||
|
||||
val actor = call.requireCurrentUser(userService)
|
||||
val chatId = call.parameters["chat_id"]
|
||||
?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id")
|
||||
|
||||
requireUuid(chatId, "chat_id")
|
||||
|
||||
val body = call.receive<CreateMessageRequest>()
|
||||
|
||||
requireNonBlankBounded(
|
||||
body.text,
|
||||
min = 1,
|
||||
max = TEXT_MAX,
|
||||
field = "text"
|
||||
)
|
||||
|
||||
val message = messageService.send(chatId, actor.id, body.text)
|
||||
call.respond(HttpStatusCode.Created, message)
|
||||
}
|
||||
|
||||
get {
|
||||
|
||||
val actor = call.requireCurrentUser(userService)
|
||||
val chatId = call.parameters["chat_id"]
|
||||
?: throw ApiException(ErrorCode.INVALID_REQUEST, "missing chat_id")
|
||||
|
||||
requireUuid(chatId, "chat_id")
|
||||
|
||||
val page = messageService.findPageByChatId(
|
||||
chatId = chatId,
|
||||
actorId = actor.id,
|
||||
rawLimit = call.request.queryParameters["limit"],
|
||||
rawCursor = call.request.queryParameters["cursor"],
|
||||
)
|
||||
|
||||
call.respond(HttpStatusCode.OK, MessagePageResponse(page.items, page.nextCursor))
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.message.requests
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CreateMessageRequest(
|
||||
val text: String,
|
||||
)
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.message.responses
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Message
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class MessagePageResponse(
|
||||
val items: List<Message>,
|
||||
val nextCursor: String?,
|
||||
)
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.user
|
||||
|
||||
import com.mtusi.messenger.main.extensions.requireCurrentUser
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest
|
||||
import com.mtusi.messenger.main.infrastructure.services.user.UserService
|
||||
import com.mtusi.messenger.main.utils.requireNonBlankBounded
|
||||
import com.mtusi.messenger.main.utils.requireUsername
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.server.request.receive
|
||||
import io.ktor.server.response.respond
|
||||
import io.ktor.server.routing.Routing
|
||||
import io.ktor.server.routing.get
|
||||
import io.ktor.server.routing.post
|
||||
import io.ktor.server.routing.route
|
||||
|
||||
private const val DISPLAY_NAME_MAX = 100
|
||||
|
||||
fun Routing.configureUserRouting(userService: UserService) = route("/api/v1/users") {
|
||||
|
||||
post {
|
||||
val body = call.receive<CreateUserRequest>()
|
||||
|
||||
requireUsername(body.username)
|
||||
|
||||
requireNonBlankBounded(
|
||||
body.displayName,
|
||||
min = 1,
|
||||
max = DISPLAY_NAME_MAX,
|
||||
field = "displayName"
|
||||
)
|
||||
|
||||
val user = userService.create(body.username, body.displayName)
|
||||
call.respond(HttpStatusCode.Created, user)
|
||||
}
|
||||
|
||||
get("me") {
|
||||
val user = call.requireCurrentUser(userService)
|
||||
call.respond(HttpStatusCode.OK, user)
|
||||
}
|
||||
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.user.requests
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CreateUserRequest(
|
||||
val username: String,
|
||||
val displayName: String,
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mtusi.messenger.main.infrastructure.dto
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Chat(
|
||||
val id: String,
|
||||
val title: String,
|
||||
val memberIds: List<String>,
|
||||
val createdAt: String,
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.mtusi.messenger.main.infrastructure.dto
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Message(
|
||||
val id: String,
|
||||
val chatId: String,
|
||||
val senderId: String,
|
||||
val text: String,
|
||||
val createdAt: String,
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mtusi.messenger.main.infrastructure.dto
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class User(
|
||||
val id: String,
|
||||
val username: String,
|
||||
val displayName: String,
|
||||
val createdAt: String,
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories
|
||||
|
||||
interface Repository<TId, TEntity>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.chat
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.Repository
|
||||
|
||||
interface ChatRepository : Repository<String, Chat> {
|
||||
fun findById(id: String): Chat?
|
||||
|
||||
fun insert(chat: Chat)
|
||||
|
||||
fun findAllAccessible(userId: String): List<Chat>
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.chat
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
class InMemoryChatRepository : ChatRepository {
|
||||
private val byId = ConcurrentHashMap<String, Chat>()
|
||||
|
||||
override fun findById(id: String): Chat? = byId[id]
|
||||
|
||||
override fun insert(chat: Chat) {
|
||||
byId[chat.id] = chat
|
||||
}
|
||||
|
||||
override fun findAllAccessible(userId: String): List<Chat> =
|
||||
byId.values
|
||||
.filter { userId in it.memberIds }
|
||||
.sortedWith(
|
||||
compareBy(
|
||||
{ it.createdAt },
|
||||
{ it.id }
|
||||
)
|
||||
)
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.message
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Message
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
|
||||
class InMemoryMessageRepository : MessageRepository {
|
||||
private val byChat = ConcurrentHashMap<String, CopyOnWriteArrayList<Message>>()
|
||||
private val locks = ConcurrentHashMap<String, Any>()
|
||||
|
||||
override fun append(
|
||||
chatId: String,
|
||||
message: Message
|
||||
) {
|
||||
|
||||
val lock = locks.computeIfAbsent(chatId) {
|
||||
Any()
|
||||
}
|
||||
|
||||
synchronized(lock) {
|
||||
byChat.computeIfAbsent(chatId) {
|
||||
CopyOnWriteArrayList()
|
||||
}.add(message)
|
||||
}
|
||||
}
|
||||
|
||||
override fun findRangeByChatId(
|
||||
chatId: String,
|
||||
offset: Int,
|
||||
count: Int,
|
||||
): List<Message> {
|
||||
|
||||
val messages = byChat[chatId]
|
||||
?: return emptyList()
|
||||
|
||||
// Append-only: indices below an observed size never change, so no snapshot copy is needed.
|
||||
val end = minOf(messages.size, offset + count)
|
||||
|
||||
if (offset >= end) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
return List(end - offset) { messages[offset + it] }
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.message
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Message
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.Repository
|
||||
|
||||
interface MessageRepository : Repository<String, Message> {
|
||||
fun append(chatId: String, message: Message)
|
||||
fun findRangeByChatId(chatId: String, offset: Int, count: Int): List<Message>
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.user
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.User
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
class InMemoryUserRepository : UserRepository {
|
||||
private val byId = ConcurrentHashMap<String, User>()
|
||||
|
||||
override fun insert(user: User) {
|
||||
byId[user.id] = user
|
||||
}
|
||||
|
||||
override fun findById(id: String): User? = byId[id]
|
||||
|
||||
override fun findByUsername(username: String): User? {
|
||||
return byId.values.find { it.username == username }
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.user
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.User
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.Repository
|
||||
|
||||
interface UserRepository : Repository<String, User> {
|
||||
fun insert(user: User)
|
||||
|
||||
fun findById(id: String): User?
|
||||
|
||||
fun findByUsername(username: String): User?
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.chat
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import com.mtusi.messenger.main.utils.Page
|
||||
|
||||
interface ChatService {
|
||||
fun create(
|
||||
creatorId: String,
|
||||
title: String,
|
||||
memberIds: List<String>,
|
||||
): Chat
|
||||
|
||||
fun findAccessible(
|
||||
userId: String,
|
||||
chatId: String,
|
||||
): Chat
|
||||
|
||||
fun findPageAccessible(
|
||||
userId: String,
|
||||
rawLimit: String?,
|
||||
rawCursor: String?,
|
||||
): Page<Chat>
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.chat
|
||||
|
||||
import com.mtusi.messenger.main.extensions.isValidUuid
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.utils.Page
|
||||
import com.mtusi.messenger.main.utils.decodeCursor
|
||||
import com.mtusi.messenger.main.utils.encodeCursor
|
||||
import com.mtusi.messenger.main.utils.nowIsoUtc
|
||||
import com.mtusi.messenger.main.utils.parseLimit
|
||||
import java.util.UUID
|
||||
|
||||
private const val MAX_MEMBERS = 100
|
||||
|
||||
class DefaultChatService(
|
||||
private val chatRepository: ChatRepository,
|
||||
private val userRepository: UserRepository,
|
||||
) : ChatService {
|
||||
|
||||
override fun create(
|
||||
creatorId: String,
|
||||
title: String,
|
||||
memberIds: List<String>,
|
||||
): Chat {
|
||||
|
||||
if (memberIds.isEmpty() || memberIds.size > MAX_MEMBERS) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "size out of range")
|
||||
}
|
||||
|
||||
if (memberIds.toSet().size != memberIds.size) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "memberIds must be unique")
|
||||
}
|
||||
|
||||
if (creatorId !in memberIds) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "creator must be in members")
|
||||
}
|
||||
|
||||
for (id in memberIds) {
|
||||
if (!isValidUuid(id))
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid member id")
|
||||
|
||||
if (userRepository.findById(id) == null)
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "unknown member")
|
||||
}
|
||||
|
||||
val chat = Chat(
|
||||
id = UUID.randomUUID().toString(),
|
||||
title = title,
|
||||
memberIds = memberIds,
|
||||
createdAt = nowIsoUtc(),
|
||||
)
|
||||
chatRepository.insert(chat)
|
||||
|
||||
return chat
|
||||
}
|
||||
|
||||
override fun findAccessible(
|
||||
userId: String,
|
||||
chatId: String,
|
||||
): Chat {
|
||||
|
||||
val chat = chatRepository.findById(chatId)
|
||||
?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found")
|
||||
|
||||
if (userId !in chat.memberIds) {
|
||||
throw ApiException(ErrorCode.NOT_FOUND, "chat not found")
|
||||
}
|
||||
|
||||
return chat
|
||||
}
|
||||
|
||||
override fun findPageAccessible(
|
||||
userId: String,
|
||||
rawLimit: String?,
|
||||
rawCursor: String?,
|
||||
): Page<Chat> {
|
||||
|
||||
val limit = parseLimit(rawLimit)
|
||||
val scope = "chats:$userId"
|
||||
val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0
|
||||
|
||||
val all = chatRepository.findAllAccessible(userId)
|
||||
val slice = all.drop(start).take(limit)
|
||||
val nextIndex = start + slice.size
|
||||
val nextCursor = if (nextIndex < all.size) encodeCursor(scope, nextIndex) else null
|
||||
|
||||
return Page(slice, nextCursor)
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.message
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Message
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.message.MessageRepository
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.utils.Page
|
||||
import com.mtusi.messenger.main.utils.decodeCursor
|
||||
import com.mtusi.messenger.main.utils.encodeCursor
|
||||
import com.mtusi.messenger.main.utils.nowIsoUtc
|
||||
import com.mtusi.messenger.main.utils.parseLimit
|
||||
import java.util.UUID
|
||||
|
||||
class DefaultMessageService(
|
||||
private val chatRepository: ChatRepository,
|
||||
private val messageRepository: MessageRepository,
|
||||
) : MessageService {
|
||||
|
||||
override fun send(
|
||||
chatId: String,
|
||||
senderId: String,
|
||||
text: String,
|
||||
): Message {
|
||||
|
||||
requireChatMembership(chatId, senderId)
|
||||
|
||||
val message = Message(
|
||||
id = UUID.randomUUID().toString(),
|
||||
chatId = chatId,
|
||||
senderId = senderId,
|
||||
text = text,
|
||||
createdAt = nowIsoUtc(),
|
||||
)
|
||||
|
||||
messageRepository.append(chatId, message)
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
override fun findPageByChatId(
|
||||
chatId: String,
|
||||
actorId: String,
|
||||
rawLimit: String?,
|
||||
rawCursor: String?,
|
||||
): Page<Message> {
|
||||
|
||||
requireChatMembership(chatId, actorId)
|
||||
|
||||
val limit = parseLimit(rawLimit)
|
||||
val scope = "messages:$chatId"
|
||||
val start = rawCursor?.let { decodeCursor(it, scope) } ?: 0
|
||||
|
||||
val window = messageRepository.findRangeByChatId(
|
||||
chatId = chatId,
|
||||
offset = start,
|
||||
count = limit + 1,
|
||||
)
|
||||
|
||||
val items = window.take(limit)
|
||||
val nextCursor = if (window.size > limit) encodeCursor(scope, start + limit) else null
|
||||
|
||||
return Page(items, nextCursor)
|
||||
}
|
||||
|
||||
private fun requireChatMembership(chatId: String, userId: String) {
|
||||
val chat = chatRepository.findById(chatId)
|
||||
?: throw ApiException(ErrorCode.NOT_FOUND, "chat not found")
|
||||
|
||||
if (userId !in chat.memberIds) {
|
||||
throw ApiException(ErrorCode.NOT_FOUND, "chat not found")
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.message
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Message
|
||||
import com.mtusi.messenger.main.utils.Page
|
||||
|
||||
interface MessageService {
|
||||
fun send(
|
||||
chatId: String,
|
||||
senderId: String,
|
||||
text: String,
|
||||
): Message
|
||||
|
||||
fun findPageByChatId(
|
||||
chatId: String,
|
||||
actorId: String,
|
||||
rawLimit: String?,
|
||||
rawCursor: String?,
|
||||
): Page<Message>
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.user
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.User
|
||||
import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import com.mtusi.messenger.main.utils.nowIsoUtc
|
||||
import java.util.UUID
|
||||
|
||||
class DefaultUserService(
|
||||
private val userRepository: UserRepository,
|
||||
) : UserService {
|
||||
|
||||
override fun create(username: String, displayName: String): User {
|
||||
|
||||
if (userRepository.findByUsername(username) != null) {
|
||||
throw ApiException(ErrorCode.CONFLICT, "username already taken")
|
||||
}
|
||||
|
||||
val user = User(
|
||||
id = UUID.randomUUID().toString(),
|
||||
username = username,
|
||||
displayName = displayName,
|
||||
createdAt = nowIsoUtc(),
|
||||
)
|
||||
|
||||
userRepository.insert(user)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
override fun findById(id: String): User? = userRepository.findById(id)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.mtusi.messenger.main.infrastructure.services.user
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.User
|
||||
|
||||
interface UserService {
|
||||
fun create(username: String, displayName: String): User
|
||||
fun findById(id: String): User?
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.mtusi.messenger.main.infrastructure.types
|
||||
|
||||
class ApiException(val code: ErrorCode, message: String) : RuntimeException(message)
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.mtusi.messenger.main.infrastructure.types
|
||||
|
||||
import io.ktor.http.HttpStatusCode
|
||||
|
||||
enum class ErrorCode(val wire: String, val status: HttpStatusCode) {
|
||||
INVALID_REQUEST("invalid_request", HttpStatusCode.BadRequest),
|
||||
UNAUTHORIZED("unauthorized", HttpStatusCode.Unauthorized),
|
||||
NOT_FOUND("not_found", HttpStatusCode.NotFound),
|
||||
CONFLICT("conflict", HttpStatusCode.Conflict),
|
||||
PAYLOAD_TOO_LARGE("payload_too_large", HttpStatusCode.PayloadTooLarge),
|
||||
UNSUPPORTED_MEDIA_TYPE("unsupported_media_type", HttpStatusCode.UnsupportedMediaType),
|
||||
RATE_LIMITED("rate_limited", HttpStatusCode.TooManyRequests),
|
||||
UNAVAILABLE("unavailable", HttpStatusCode.ServiceUnavailable),
|
||||
INTERNAL_ERROR("internal_error", HttpStatusCode.InternalServerError),
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.plugins.calllogging.CallLogging
|
||||
import org.slf4j.event.Level
|
||||
|
||||
fun Application.configureCallLogging() = install(CallLogging) {
|
||||
level = Level.INFO
|
||||
filter { call ->
|
||||
val uri = call.request.local.uri
|
||||
uri.startsWith("/api") || uri.startsWith("/health")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonNamingStrategy
|
||||
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
val json = Json {
|
||||
ignoreUnknownKeys = false
|
||||
explicitNulls = true
|
||||
encodeDefaults = true
|
||||
namingStrategy = JsonNamingStrategy.SnakeCase
|
||||
}
|
||||
|
||||
fun Application.configureContentNegotiation() = install(ContentNegotiation) {
|
||||
json(json)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.plugins.defaultheaders.DefaultHeaders
|
||||
|
||||
fun Application.configureDefaultHeaders() = install(DefaultHeaders)
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.services.chat.ChatService
|
||||
import com.mtusi.messenger.main.infrastructure.services.message.MessageService
|
||||
import com.mtusi.messenger.main.infrastructure.services.user.UserService
|
||||
|
||||
data class Dependencies(
|
||||
val userService: UserService,
|
||||
val chatService: ChatService,
|
||||
val messageService: MessageService,
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.createApplicationPlugin
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.util.AttributeKey
|
||||
import java.util.UUID
|
||||
|
||||
val RequestIdKey: AttributeKey<String> = AttributeKey("X-Request-Id")
|
||||
|
||||
private val RequestIdPlugin = createApplicationPlugin("RequestId") {
|
||||
onCall { call ->
|
||||
val incoming = call.request.headers["X-Request-Id"]?.takeIf { it.isNotBlank() }
|
||||
val id = incoming ?: UUID.randomUUID().toString()
|
||||
call.attributes.put(RequestIdKey, id)
|
||||
call.response.headers.append("X-Request-Id", id, safeOnly = false)
|
||||
}
|
||||
}
|
||||
|
||||
fun Application.configureRequestId() = install(RequestIdPlugin)
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.chat.configureChatRouting
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.health.configureHealthRouting
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.configureMessageRouting
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.user.configureUserRouting
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.routing.routing
|
||||
|
||||
fun Application.configureRouting(dependencies: Dependencies) = routing {
|
||||
configureSwaggerRouting()
|
||||
configureHealthRouting()
|
||||
configureUserRouting(dependencies.userService)
|
||||
configureChatRouting(dependencies.chatService, dependencies.userService)
|
||||
configureMessageRouting(dependencies.messageService, dependencies.userService)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import com.mtusi.messenger.main.extensions.respondError
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.serialization.JsonConvertException
|
||||
import io.ktor.server.application.Application
|
||||
import io.ktor.server.application.install
|
||||
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 kotlinx.serialization.SerializationException
|
||||
|
||||
fun Application.configureStatusPages() = install(StatusPages) {
|
||||
exception<ApiException> { call, cause ->
|
||||
call.respondError(cause.code, cause.message ?: cause.code.wire)
|
||||
}
|
||||
exception<JsonConvertException> { call, _ ->
|
||||
call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body")
|
||||
}
|
||||
exception<SerializationException> { call, _ ->
|
||||
call.respondError(ErrorCode.INVALID_REQUEST, "invalid JSON body")
|
||||
}
|
||||
exception<BadRequestException> { call, _ ->
|
||||
call.respondError(ErrorCode.INVALID_REQUEST, "invalid request")
|
||||
}
|
||||
exception<NotFoundException> { call, _ ->
|
||||
call.respondError(ErrorCode.NOT_FOUND, "not found")
|
||||
}
|
||||
exception<UnsupportedMediaTypeException> { call, _ ->
|
||||
call.respondError(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "unsupported media type")
|
||||
}
|
||||
exception<Throwable> { call, _ ->
|
||||
call.respondError(ErrorCode.INTERNAL_ERROR, "internal error")
|
||||
}
|
||||
status(HttpStatusCode.NotFound) { call, _ ->
|
||||
call.respondError(ErrorCode.NOT_FOUND, "not found")
|
||||
}
|
||||
status(HttpStatusCode.MethodNotAllowed) { call, _ ->
|
||||
call.respondError(ErrorCode.NOT_FOUND, "not found")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.mtusi.messenger.main.plugins
|
||||
|
||||
import io.ktor.server.plugins.swagger.swaggerUI
|
||||
import io.ktor.server.routing.Routing
|
||||
|
||||
fun Routing.configureSwaggerRouting() {
|
||||
swaggerUI(path = "docs", swaggerFile = "openapi.json")
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.mtusi.messenger.main.utils
|
||||
|
||||
data class Page<T>(
|
||||
val items: List<T>,
|
||||
val nextCursor: String?,
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.mtusi.messenger.main.utils
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
import java.util.Base64
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
private const val DEFAULT_LIMIT = 50
|
||||
private const val MAX_LIMIT = 100
|
||||
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
@Serializable
|
||||
private data class Cursor(val scope: String, val index: Int)
|
||||
|
||||
fun encodeCursor(scope: String, index: Int): String {
|
||||
val raw = json.encodeToString(Cursor.serializer(), Cursor(scope, index))
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.toByteArray(Charsets.UTF_8))
|
||||
}
|
||||
|
||||
fun decodeCursor(raw: String, expectedScope: String): Int {
|
||||
val decoded = try {
|
||||
val bytes = Base64.getUrlDecoder().decode(raw)
|
||||
json.decodeFromString(Cursor.serializer(), String(bytes, Charsets.UTF_8))
|
||||
} catch (_: Throwable) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid cursor")
|
||||
}
|
||||
if (decoded.scope != expectedScope || decoded.index < 0) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "cursor does not belong to this resource")
|
||||
}
|
||||
return decoded.index
|
||||
}
|
||||
|
||||
fun parseLimit(raw: String?): Int {
|
||||
if (raw == null) return DEFAULT_LIMIT
|
||||
val v = raw.toIntOrNull() ?: throw ApiException(ErrorCode.INVALID_REQUEST, "invalid limit")
|
||||
if (v !in 1..MAX_LIMIT) throw ApiException(ErrorCode.INVALID_REQUEST, "limit out of range")
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.mtusi.messenger.main.utils
|
||||
|
||||
import java.time.Instant
|
||||
import java.time.ZoneOffset
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
private val RFC3339: DateTimeFormatter = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
|
||||
.withZone(ZoneOffset.UTC)
|
||||
|
||||
fun nowIsoUtc(): String = RFC3339.format(Instant.now())
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.mtusi.messenger.main.utils
|
||||
|
||||
import com.mtusi.messenger.main.extensions.isValidUuid
|
||||
import com.mtusi.messenger.main.infrastructure.types.ApiException
|
||||
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
|
||||
|
||||
private val USERNAME = Regex("^[a-z0-9_]{3,32}$")
|
||||
|
||||
fun codePoints(value: String): Int = value.codePointCount(0, value.length)
|
||||
|
||||
fun requireUsername(value: String) {
|
||||
if (!USERNAME.matches(value)) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid username")
|
||||
}
|
||||
}
|
||||
|
||||
fun requireNonBlankBounded(value: String, min: Int, max: Int, field: String) {
|
||||
if (value.isBlank()) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "$field must not be blank")
|
||||
}
|
||||
val n = codePoints(value)
|
||||
if (n !in min..max) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "$field length out of range")
|
||||
}
|
||||
}
|
||||
|
||||
fun requireUuid(value: String, field: String) {
|
||||
if (!isValidUuid(value)) {
|
||||
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid $field")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
ktor {
|
||||
application {
|
||||
modules = [com.mtusi.messenger.main.AppKt.module]
|
||||
}
|
||||
|
||||
deployment {
|
||||
host = "0.0.0.0"
|
||||
host = ${?APP_HOST}
|
||||
port = 8080
|
||||
port = ${?APP_PORT}
|
||||
shutdownGracePeriod = 3000
|
||||
shutdownTimeout = 10000
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%thread] %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
<logger name="io.netty" level="WARN"/>
|
||||
<logger name="org.eclipse.jetty" level="WARN"/>
|
||||
</configuration>
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.chat
|
||||
|
||||
import com.mtusi.messenger.main.extensions.ErrorBody
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import com.mtusi.messenger.main.support.createChat
|
||||
import com.mtusi.messenger.main.support.createUser
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class ChatControllerTest {
|
||||
|
||||
@Test
|
||||
fun `foreign chat returns 404 for non-member`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val bob = client.createUser("bob")
|
||||
val chat = client.createChat(alice, title = "secret", memberIds = listOf(alice.id))
|
||||
|
||||
val response = client.get("/api/v1/chats/${chat.id}") {
|
||||
header("X-User-Id", bob.id)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
assertEquals("not_found", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `member can read own chat`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val created = client.createChat(alice, title = "notes", memberIds = listOf(alice.id))
|
||||
|
||||
val response = client.get("/api/v1/chats/${created.id}") {
|
||||
header("X-User-Id", alice.id)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
assertEquals(created.id, response.body<Chat>().id)
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.health
|
||||
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class HealthControllerTest {
|
||||
|
||||
@Test
|
||||
fun `live returns 200`() = runApp { client ->
|
||||
val response = client.get("/health/live")
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ready returns 200`() = runApp { client ->
|
||||
val response = client.get("/health/ready")
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.message
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse
|
||||
import com.mtusi.messenger.main.support.createChat
|
||||
import com.mtusi.messenger.main.support.createUser
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.contentType
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class MessageConcurrencyTest {
|
||||
|
||||
@Test
|
||||
fun `parallel senders produce exactly N unique messages`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val chat = client.createChat(alice, title = "load", memberIds = listOf(alice.id))
|
||||
|
||||
val workers = 10
|
||||
val perWorker = 10
|
||||
val total = workers * perWorker
|
||||
|
||||
coroutineScope {
|
||||
(0 until workers).map { w ->
|
||||
async {
|
||||
repeat(perWorker) { i ->
|
||||
val response = client.post("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "w$w-i$i"))
|
||||
}
|
||||
assertEquals(HttpStatusCode.Created, response.status)
|
||||
}
|
||||
}
|
||||
}.awaitAll()
|
||||
}
|
||||
|
||||
val collected = mutableListOf<String>()
|
||||
var cursor: String? = null
|
||||
|
||||
do {
|
||||
val response = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
url {
|
||||
parameters.append("limit", "100")
|
||||
if (cursor != null) parameters.append("cursor", cursor!!)
|
||||
}
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
|
||||
val page = response.body<MessagePageResponse>()
|
||||
collected += page.items.map { it.text }
|
||||
cursor = page.nextCursor
|
||||
} while (cursor != null)
|
||||
|
||||
assertEquals(total, collected.size)
|
||||
assertEquals(total, collected.toSet().size)
|
||||
|
||||
val expected = buildSet {
|
||||
for (w in 0 until workers) for (i in 0 until perWorker) add("w$w-i$i")
|
||||
}
|
||||
assertEquals(expected, collected.toSet())
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.message
|
||||
|
||||
import com.mtusi.messenger.main.extensions.ErrorBody
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.message.responses.MessagePageResponse
|
||||
import com.mtusi.messenger.main.support.createChat
|
||||
import com.mtusi.messenger.main.support.createUser
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.contentType
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
|
||||
class MessageControllerTest {
|
||||
|
||||
@Test
|
||||
fun `empty text returns 400 invalid_request`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id))
|
||||
|
||||
val response = client.post("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = ""))
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
assertEquals("invalid_request", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreign chat returns 404 when sending`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val bob = client.createUser("bob")
|
||||
val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id))
|
||||
|
||||
val response = client.post("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", bob.id)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "hi"))
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
assertEquals("not_found", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreign chat returns 404 when listing`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val bob = client.createUser("bob")
|
||||
val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id))
|
||||
|
||||
val response = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", bob.id)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.NotFound, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `pagination walks all messages exactly once`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id))
|
||||
|
||||
val total = 25
|
||||
repeat(total) { i ->
|
||||
val r = client.post("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "m$i"))
|
||||
}
|
||||
assertEquals(HttpStatusCode.Created, r.status)
|
||||
}
|
||||
|
||||
val collected = mutableListOf<String>()
|
||||
var cursor: String? = null
|
||||
var pages = 0
|
||||
|
||||
do {
|
||||
val response = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
url {
|
||||
parameters.append("limit", "10")
|
||||
if (cursor != null) parameters.append("cursor", cursor!!)
|
||||
}
|
||||
}
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
|
||||
val page = response.body<MessagePageResponse>()
|
||||
collected += page.items.map { it.text }
|
||||
cursor = page.nextCursor
|
||||
pages++
|
||||
} while (cursor != null)
|
||||
|
||||
assertEquals(3, pages)
|
||||
assertEquals(total, collected.size)
|
||||
assertEquals(total, collected.toSet().size)
|
||||
assertEquals((0 until total).map { "m$it" }, collected)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `history that is an exact multiple of limit ends with null next_cursor`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id))
|
||||
|
||||
repeat(20) { i ->
|
||||
client.post("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "m$i"))
|
||||
}
|
||||
}
|
||||
|
||||
val first = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
url { parameters.append("limit", "10") }
|
||||
}.body<MessagePageResponse>()
|
||||
|
||||
val cursor = first.nextCursor
|
||||
assertNotNull(cursor)
|
||||
|
||||
val second = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
url {
|
||||
parameters.append("limit", "10")
|
||||
parameters.append("cursor", cursor)
|
||||
}
|
||||
}.body<MessagePageResponse>()
|
||||
|
||||
assertEquals((10 until 20).map { "m$it" }, second.items.map { it.text })
|
||||
assertNull(second.nextCursor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `last page has null next_cursor`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val chat = client.createChat(alice, title = "t", memberIds = listOf(alice.id))
|
||||
|
||||
val response = client.get("/api/v1/chats/${chat.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.OK, response.status)
|
||||
val page = response.body<MessagePageResponse>()
|
||||
assertEquals(0, page.items.size)
|
||||
assertNull(page.nextCursor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `foreign cursor returns 400`() = runApp { client ->
|
||||
val alice = client.createUser("alice")
|
||||
val chatA = client.createChat(alice, title = "a", memberIds = listOf(alice.id))
|
||||
val chatB = client.createChat(alice, title = "b", memberIds = listOf(alice.id))
|
||||
|
||||
repeat(2) { i ->
|
||||
client.post("/api/v1/chats/${chatA.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateMessageRequest(text = "a$i"))
|
||||
}
|
||||
}
|
||||
|
||||
val firstA = client.get("/api/v1/chats/${chatA.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
url { parameters.append("limit", "1") }
|
||||
}.body<MessagePageResponse>()
|
||||
|
||||
val cursor = firstA.nextCursor
|
||||
assertNotNull(cursor)
|
||||
|
||||
val response = client.get("/api/v1/chats/${chatB.id}/messages") {
|
||||
header("X-User-Id", alice.id)
|
||||
url {
|
||||
parameters.append("limit", "1")
|
||||
parameters.append("cursor", cursor)
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
assertEquals("invalid_request", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package com.mtusi.messenger.main.infrastructure.controllers.user
|
||||
|
||||
import com.mtusi.messenger.main.extensions.ErrorBody
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest
|
||||
import com.mtusi.messenger.main.support.createUser
|
||||
import com.mtusi.messenger.main.support.runApp
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.contentType
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
|
||||
class UserControllerTest {
|
||||
|
||||
@Test
|
||||
fun `create user returns 201 and echoes fields`() = runApp { client ->
|
||||
val response = client.post("/api/v1/users") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateUserRequest(username = "alice", displayName = "Alice"))
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.Created, response.status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `invalid JSON body returns 400 invalid_request`() = runApp { client ->
|
||||
val response = client.post("/api/v1/users") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody("{not json")
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.BadRequest, response.status)
|
||||
|
||||
val body = response.body<ErrorBody>()
|
||||
assertEquals("invalid_request", body.error.code)
|
||||
assertNotNull(body.error.requestId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `duplicate username returns 409 conflict`() = runApp { client ->
|
||||
client.createUser(username = "bob")
|
||||
|
||||
val response = client.post("/api/v1/users") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateUserRequest(username = "bob", displayName = "Bob 2"))
|
||||
}
|
||||
|
||||
assertEquals(HttpStatusCode.Conflict, response.status)
|
||||
assertEquals("conflict", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing X-User-Id on protected endpoint returns 401`() = runApp { client ->
|
||||
val response = client.get("/api/v1/users/me")
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
assertEquals("unauthorized", response.body<ErrorBody>().error.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown X-User-Id returns 401`() = runApp { client ->
|
||||
val response = client.get("/api/v1/users/me") {
|
||||
header("X-User-Id", "00000000-0000-0000-0000-000000000000")
|
||||
}
|
||||
assertEquals(HttpStatusCode.Unauthorized, response.status)
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.mtusi.messenger.main.infrastructure.repositories.message
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Message
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
private const val CHAT_ID = "chat"
|
||||
|
||||
class InMemoryMessageRepositoryTest {
|
||||
|
||||
private fun repositoryWith(size: Int): InMemoryMessageRepository {
|
||||
|
||||
val repository = InMemoryMessageRepository()
|
||||
|
||||
repeat(size) { i ->
|
||||
repository.append(
|
||||
CHAT_ID,
|
||||
Message(
|
||||
id = "m$i",
|
||||
chatId = CHAT_ID,
|
||||
senderId = "u",
|
||||
text = "t$i",
|
||||
createdAt = "2026-01-01T00:00:00.000Z",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
return repository
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `returns requested window in append order`() {
|
||||
val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 3, count = 4)
|
||||
assertEquals(listOf("m3", "m4", "m5", "m6"), range.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `window is clipped at the end of history`() {
|
||||
val range = repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 8, count = 5)
|
||||
assertEquals(listOf("m8", "m9"), range.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `offset past the end returns empty`() {
|
||||
assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = 10, count = 5).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `huge offset does not overflow`() {
|
||||
assertTrue(repositoryWith(10).findRangeByChatId(CHAT_ID, offset = Int.MAX_VALUE - 1, count = 51).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `unknown chat returns empty`() {
|
||||
assertTrue(InMemoryMessageRepository().findRangeByChatId("missing", offset = 0, count = 50).isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.mtusi.messenger.main.support
|
||||
|
||||
import com.mtusi.messenger.main.infrastructure.dto.Chat
|
||||
import com.mtusi.messenger.main.infrastructure.dto.User
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest
|
||||
import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest
|
||||
import com.mtusi.messenger.main.module
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.client.request.header
|
||||
import io.ktor.client.request.post
|
||||
import io.ktor.client.request.setBody
|
||||
import io.ktor.client.statement.HttpResponse
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.http.HttpHeaders
|
||||
import io.ktor.http.HttpStatusCode
|
||||
import io.ktor.http.contentType
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import io.ktor.server.testing.ApplicationTestBuilder
|
||||
import io.ktor.server.testing.testApplication
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonNamingStrategy
|
||||
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
val testJson = Json {
|
||||
ignoreUnknownKeys = true
|
||||
encodeDefaults = true
|
||||
namingStrategy = JsonNamingStrategy.SnakeCase
|
||||
}
|
||||
|
||||
fun runApp(block: suspend ApplicationTestBuilder.(HttpClient) -> Unit) = testApplication {
|
||||
application {
|
||||
module()
|
||||
}
|
||||
val client = createClient {
|
||||
install(ContentNegotiation) {
|
||||
json(testJson)
|
||||
}
|
||||
}
|
||||
block(client)
|
||||
}
|
||||
|
||||
suspend fun HttpClient.createUser(username: String, displayName: String = username): User {
|
||||
val response = post("/api/v1/users") {
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateUserRequest(username = username, displayName = displayName))
|
||||
}
|
||||
check(response.status == HttpStatusCode.Created) { "createUser failed: ${response.status}" }
|
||||
return response.body()
|
||||
}
|
||||
|
||||
suspend fun HttpClient.createChat(
|
||||
creator: User,
|
||||
title: String,
|
||||
memberIds: List<String>,
|
||||
): Chat {
|
||||
val response = post("/api/v1/chats") {
|
||||
header("X-User-Id", creator.id)
|
||||
contentType(ContentType.Application.Json)
|
||||
setBody(CreateChatRequest(title = title, memberIds = memberIds))
|
||||
}
|
||||
check(response.status == HttpStatusCode.Created) { "createChat failed: ${response.status}" }
|
||||
return response.body()
|
||||
}
|
||||
|
||||
fun HttpResponse.header(name: String): String? = headers[name]
|
||||
|
||||
val HttpResponse.requestId: String?
|
||||
get() = headers[HttpHeaders.XRequestId]
|
||||
@@ -0,0 +1,10 @@
|
||||
ktor {
|
||||
application {
|
||||
modules = [com.mtusi.messenger.main.AppKt.module]
|
||||
}
|
||||
|
||||
deployment {
|
||||
host = "127.0.0.1"
|
||||
port = 0
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user