Move lab1 to lab2

This commit is contained in:
2026-10-08 13:40:27 +03:00
parent 65003b6119
commit 16fa679bc0
65 changed files with 2063 additions and 0 deletions
@@ -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")
}
@@ -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)
}
}
@@ -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>,
)
@@ -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?,
)
@@ -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())
}
}
@@ -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")
@@ -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))
}
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.controllers.message.requests
import kotlinx.serialization.Serializable
@Serializable
data class CreateMessageRequest(
val text: String,
)
@@ -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?,
)
@@ -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)
}
}
@@ -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>
@@ -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>
}
@@ -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 }
)
)
}
@@ -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] }
}
}
@@ -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>
}
@@ -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 }
}
}
@@ -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>
}
@@ -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)
}
}
@@ -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")
}
}
}
@@ -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>
}
@@ -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")
}
}
+14
View File
@@ -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
}
}
+12
View File
@@ -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>