Move lab4 to lab5

This commit is contained in:
2026-11-16 19:54:38 +03:00
parent 276dbdad8a
commit cd84a6fd36
208 changed files with 9611 additions and 25 deletions
@@ -0,0 +1,50 @@
package com.mtusi.messenger.main
import com.mtusi.messenger.main.plugins.authentication.configureAuthentication
import com.mtusi.messenger.main.plugins.configureAttachmentCleanup
import com.mtusi.messenger.main.plugins.configureCallLogging
import com.mtusi.messenger.main.plugins.configureContentNegotiation
import com.mtusi.messenger.main.plugins.configureCors
import com.mtusi.messenger.main.plugins.configureDatabase
import com.mtusi.messenger.main.plugins.configureDefaultHeaders
import com.mtusi.messenger.main.plugins.configureGracefulShutdown
import com.mtusi.messenger.main.plugins.configureInstanceId
import com.mtusi.messenger.main.plugins.configureKoin
import com.mtusi.messenger.main.plugins.configureRedis
import com.mtusi.messenger.main.plugins.configureRequestId
import com.mtusi.messenger.main.plugins.configureSessionRevocationSync
import com.mtusi.messenger.main.plugins.configureRouting
import com.mtusi.messenger.main.plugins.configureStatusPages
import com.mtusi.messenger.main.plugins.migrateDatabase
import io.ktor.server.application.Application
import io.ktor.server.netty.EngineMain
fun main(args: Array<String>) {
// `migrate` applies database migrations and exits; the API replicas start with migrations already in place.
if (args.firstOrNull() == "migrate") {
return migrateDatabase()
}
EngineMain.main(args)
}
fun Application.module() {
configureKoin()
configureDatabase()
configureRedis()
configureGracefulShutdown()
configureSessionRevocationSync()
configureAttachmentCleanup()
configureContentNegotiation()
configureDefaultHeaders()
configureInstanceId()
configureCors()
configureRequestId()
configureCallLogging()
configureStatusPages()
configureAuthentication()
configureRouting()
}
@@ -0,0 +1,31 @@
package com.mtusi.messenger.main.compat.serializers
import io.ktor.http.HttpMethod
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
typealias SerialHttpMethod = @Serializable(HttpMethodSerializer::class) HttpMethod
object HttpMethodSerializer : KSerializer<HttpMethod> {
override val descriptor = PrimitiveSerialDescriptor(
serialName = "HttpMethod",
kind = PrimitiveKind.STRING
)
override fun serialize(
encoder: Encoder,
value: HttpMethod
) {
encoder.encodeString(value.value)
}
override fun deserialize(decoder: Decoder): HttpMethod {
return HttpMethod.parse(decoder.decodeString())
}
}
@@ -0,0 +1,31 @@
package com.mtusi.messenger.main.compat.serializers
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.util.UUID
typealias SerialUUID = @Serializable(UUIDSerializer::class) UUID
object UUIDSerializer : KSerializer<UUID> {
override val descriptor = PrimitiveSerialDescriptor(
serialName = "UUID",
kind = PrimitiveKind.STRING
)
override fun deserialize(decoder: Decoder): UUID {
return decoder.decodeString().run(UUID::fromString)
}
override fun serialize(
encoder: Encoder,
value: UUID
) {
encoder.encodeString(value.toString())
}
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.config
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
@Module(createdAtStart = true)
@ComponentScan
class ConfigModule
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.config.authentication
interface AuthenticationConfig {
val realm: String
val sessionTtlSeconds: Long
val sessionCacheTtlSeconds: Long
val sessionCacheSingleFlight: Boolean
/**
* How long a logout keeps trying to write its tombstone to Redis before it answers 503 instead of 204.
*/
val sessionRevokeTimeoutMs: Long
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.authentication
import io.ktor.server.application.Application
import io.ktor.server.config.getAs
import org.koin.core.annotation.Provided
import org.koin.core.annotation.Single
@Single
class DefaultAuthenticationConfig(
@Provided app: Application
) : AuthenticationConfig by app.environment.config.property("authentication").getAs<SerialAuthenticationConfig>()
@@ -0,0 +1,12 @@
package com.mtusi.messenger.main.config.authentication
import kotlinx.serialization.Serializable
@Serializable
data class SerialAuthenticationConfig(
override val realm: String,
override val sessionTtlSeconds: Long,
override val sessionCacheTtlSeconds: Long,
override val sessionCacheSingleFlight: Boolean = true,
override val sessionRevokeTimeoutMs: Long = 8000
) : AuthenticationConfig
@@ -0,0 +1,100 @@
package com.mtusi.messenger.main.config.cors
import com.mtusi.messenger.main.compat.serializers.SerialHttpMethod
import io.ktor.http.HttpMethod
import kotlinx.serialization.Serializable
import io.ktor.server.plugins.cors.CORSConfig as CorsPluginConfig
interface CorsConfig {
/**
* Whether any host should be allowed
*
* Must default to false
*/
val allowAnyHost: Boolean
val allowedHosts: List<AllowedHost>
/**
* Whether any [HttpMethod][io.ktor.http.HttpMethod] should be allowed
*
* Must default to true
*/
val allowAnyMethod: Boolean
val allowedMethods: List<SerialHttpMethod>
/**
* Whether any header should be allowed
*
* Must default to true
*/
val allowAnyHeader: Boolean
val allowedHeaders: List<String>
/**
* Response headers a browser page may read, e.g. X-Request-Id and X-Instance-Id in Swagger UI
*/
val exposedHeaders: List<String>
/**
* Whether requests from the API's own origin should be allowed
*
* Must default to false
*/
val allowSameOrigin: Boolean
/**
* Whether credentials should be allowed
*
* Must default to true
*/
val allowCredentials: Boolean
/**
* Whether non-simple content types should be allowed
*
* Must default to true
*
* @see [io.ktor.server.plugins.cors.CORSConfig.allowNonSimpleContentTypes]
*/
val allowNonSimpleContentTypes: Boolean
@Serializable
data class AllowedHost(
val host: String,
val schemes: List<String>
)
}
fun CorsPluginConfig.configure(config: CorsConfig) {
if (config.allowAnyHost) {
anyHost()
} else {
config.allowedHosts.forEach { (host, schemes) ->
allowHost(host, schemes)
}
}
if (config.allowAnyMethod) {
HttpMethod.DefaultMethods.forEach(::allowMethod)
} else {
config.allowedMethods.forEach(::allowMethod)
}
if (config.allowAnyHeader) {
allowHeaders { true }
} else {
config.allowedHeaders.forEach(::allowHeader)
}
config.exposedHeaders.forEach(::exposeHeader)
allowSameOrigin = config.allowSameOrigin
allowCredentials = config.allowCredentials
allowNonSimpleContentTypes = config.allowNonSimpleContentTypes
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.cors
import io.ktor.server.application.Application
import io.ktor.server.config.getAs
import org.koin.core.annotation.Provided
import org.koin.core.annotation.Single
@Single
class DefaultCorsConfig(
@Provided app: Application
) : CorsConfig by app.environment.config.property("cors").getAs<SerialCorsConfig>()
@@ -0,0 +1,18 @@
package com.mtusi.messenger.main.config.cors
import com.mtusi.messenger.main.compat.serializers.SerialHttpMethod
import kotlinx.serialization.Serializable
@Serializable
data class SerialCorsConfig(
override val allowAnyHost: Boolean = false,
override val allowedHosts: List<CorsConfig.AllowedHost> = emptyList(),
override val allowAnyMethod: Boolean = true,
override val allowedMethods: List<SerialHttpMethod> = emptyList(),
override val allowAnyHeader: Boolean = true,
override val allowedHeaders: List<String> = emptyList(),
override val exposedHeaders: List<String> = emptyList(),
override val allowSameOrigin: Boolean = false,
override val allowCredentials: Boolean = true,
override val allowNonSimpleContentTypes: Boolean = true
) : CorsConfig
@@ -0,0 +1,22 @@
package com.mtusi.messenger.main.config.database
interface DatabaseConfig {
val host: String
val port: Int
val name: String
val username: String
val password: String?
val passwordFile: String?
val maxPoolSize: Int
val connectionTimeoutMs: Long
val statementTimeoutMs: Long
val migrateOnStart: Boolean
val jdbcConnectionUrl: String
get() = "jdbc:postgresql://$host:$port/$name"
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.database
import io.ktor.server.application.Application
import io.ktor.server.config.getAs
import org.koin.core.annotation.Provided
import org.koin.core.annotation.Single
@Single
class DefaultDatabaseConfig(
@Provided app: Application
) : DatabaseConfig by app.environment.config.property("database").getAs<SerialDatabaseConfig>()
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.config.database
import kotlinx.serialization.Serializable
@Serializable
data class SerialDatabaseConfig(
override val host: String,
override val port: Int,
override val name: String,
override val username: String,
override val password: String? = null,
override val passwordFile: String? = null,
override val maxPoolSize: Int,
override val connectionTimeoutMs: Long,
override val statementTimeoutMs: Long,
override val migrateOnStart: Boolean = true
) : DatabaseConfig
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.message
import io.ktor.server.application.Application
import io.ktor.server.config.getAs
import org.koin.core.annotation.Provided
import org.koin.core.annotation.Single
@Single
class DefaultMessageConfig(
@Provided app: Application
) : MessageConfig by app.environment.config.propertyOrNull("messages")?.getAs<SerialMessageConfig>() ?: SerialMessageConfig()
@@ -0,0 +1,5 @@
package com.mtusi.messenger.main.config.message
interface MessageConfig {
val idempotencyTtlSeconds: Long
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.config.message
import kotlinx.serialization.Serializable
@Serializable
data class SerialMessageConfig(
override val idempotencyTtlSeconds: Long = 86400
) : MessageConfig
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.config.redis
import io.ktor.server.application.Application
import io.ktor.server.config.getAs
import org.koin.core.annotation.Provided
import org.koin.core.annotation.Single
@Single
class DefaultRedisConfig(
@Provided app: Application
) : RedisConfig by app.environment.config.property("redis").getAs<SerialRedisConfig>()
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.config.redis
interface RedisConfig {
val host: String
val port: Int
val username: String?
val password: String?
val passwordFile: String?
val connectTimeoutMs: Long
val commandTimeoutMs: Long
}
@@ -0,0 +1,14 @@
package com.mtusi.messenger.main.config.redis
import kotlinx.serialization.Serializable
@Serializable
data class SerialRedisConfig(
override val host: String,
override val port: Int,
override val username: String? = null,
override val password: String? = null,
override val passwordFile: String? = null,
override val connectTimeoutMs: Long,
override val commandTimeoutMs: Long
) : RedisConfig
@@ -0,0 +1,12 @@
package com.mtusi.messenger.main.config.storage
import io.ktor.server.application.Application
import io.ktor.server.config.getAs
import org.koin.core.annotation.Provided
import org.koin.core.annotation.Single
@Single
class DefaultStorageConfig(
@Provided app: Application
) : StorageConfig by
(app.environment.config.propertyOrNull("storage")?.getAs<SerialStorageConfig>() ?: SerialStorageConfig())
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.config.storage
import kotlinx.serialization.Serializable
@Serializable
data class SerialStorageConfig(
override val endpoint: String = "http://localhost:9000",
override val bucket: String = "attachments",
override val accessKey: String? = null,
override val secretKey: String? = null,
override val accessKeyFile: String? = null,
override val secretKeyFile: String? = null,
) : StorageConfig
@@ -0,0 +1,10 @@
package com.mtusi.messenger.main.config.storage
interface StorageConfig {
val endpoint: String
val bucket: String
val accessKey: String?
val secretKey: String?
val accessKeyFile: String?
val secretKeyFile: String?
}
@@ -0,0 +1,37 @@
package com.mtusi.messenger.main.extensions
import com.mtusi.messenger.main.infrastructure.types.AuthChallenge
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.RequestIdKey
import com.mtusi.messenger.main.plugins.authentication.UserPrincipal
import io.ktor.http.HttpHeaders
import io.ktor.server.application.ApplicationCall
import io.ktor.server.auth.principal
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,
challenge: String = AuthChallenge.BEARER,
) {
val requestId = attributes[RequestIdKey]
if (code == ErrorCode.UNAUTHORIZED) {
response.header(HttpHeaders.WWWAuthenticate, challenge)
}
respond(code.status, ErrorBody(ErrorDetails(code.wire, message, requestId)))
}
val ApplicationCall.currentUser: UserPrincipal
get() = principal<UserPrincipal>()!!
@@ -0,0 +1,31 @@
package com.mtusi.messenger.main.infrastructure.controllers._common.parameters
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import io.ktor.server.application.ApplicationCall
private const val DEFAULT_LIMIT = 50
private const val MAX_LIMIT = 100
data class PageParameters(
val limit: Int,
val cursor: String?
)
fun ApplicationCall.pageParameters(): PageParameters {
val query = request.queryParameters
val limit = query["limit"]
?.let { it.toIntOrNull() ?: throw ApiException(ErrorCode.INVALID_REQUEST, "invalid limit") }
?: DEFAULT_LIMIT
if (limit !in 1..MAX_LIMIT) {
throw ApiException(ErrorCode.INVALID_REQUEST, "limit out of range")
}
val cursor = query["cursor"]
?.takeIf { it.isNotEmpty() }
return PageParameters(limit, cursor)
}
@@ -0,0 +1,106 @@
package com.mtusi.messenger.main.infrastructure.controllers.attachment
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.infrastructure.services.attachment.AttachmentService
import com.mtusi.messenger.main.infrastructure.services.attachment.MAX_ATTACHMENT_BYTES
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.utils.requireUuid
import io.ktor.http.*
import io.ktor.server.auth.authenticate
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.withTimeoutOrNull
import org.koin.ktor.ext.inject
import com.mtusi.messenger.main.utils.withTemporaryUpload
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlin.time.Duration.Companion.milliseconds
fun Routing.configureAttachmentRouting() {
val service by inject<AttachmentService>()
val uploads = Semaphore(1)
authenticate(SESSION_AUTH) {
post("/api/v1/chats/{chat_id}/attachments") {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
service.requireMember(chatId, actor.id)
val filename = call.request.queryParameters["filename"]
?: throw ApiException(ErrorCode.INVALID_REQUEST, "filename is required")
if (filename.isBlank() || filename.codePointCount(0, filename.length) !in 1..255 || filename.any { it == '/' || it == '\\' || it.isISOControl() }) {
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid filename")
}
val type = try {
call.request.contentType().withoutParameters().toString().lowercase()
} catch (_: BadContentTypeFormatException) {
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid Content-Type")
}
if (type !in setOf("image/png", "image/jpeg")) {
throw ApiException(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "expected PNG or JPEG")
}
if ((call.request.contentLength() ?: 0) > MAX_ATTACHMENT_BYTES) {
throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "file exceeds 10 MiB")
}
uploads.withPermit {
withTemporaryUpload { file ->
withTimeoutOrNull(15_000.milliseconds) {
withContext(Dispatchers.IO) {
val input = call.receiveChannel()
val buffer = ByteArray(8192)
var size = 0L
file.outputStream().use { output ->
while (true) {
val count = input.readAvailable(buffer)
if (count == -1) break
size += count
if (size > MAX_ATTACHMENT_BYTES) {
throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "file exceeds 10 MiB")
}
output.write(buffer, 0, count)
}
}
}
} ?: throw ApiException(ErrorCode.INVALID_REQUEST, "upload timed out")
val attachment = service.upload(chatId, actor.id, filename, type, file)
call.respond(HttpStatusCode.Created, attachment)
}
}
}
get("/api/v1/attachments/{id}") {
call.respond(service.find(requireUuid(call.parameters["id"], "id"), call.currentUser.id))
}
get("/api/v1/attachments/{id}/content") {
val attachment = service.find(requireUuid(call.parameters["id"], "id"), call.currentUser.id)
if ((call.request.queryParameters["variant"] ?: "original") != "original") {
throw ApiException(ErrorCode.NOT_FOUND, "variant not found")
}
call.response.header(HttpHeaders.CacheControl, "private, no-store")
call.response.header("X-Content-Type-Options", "nosniff")
call.respondBytes(service.content(attachment), ContentType.parse(attachment.contentType))
}
}
}
@@ -0,0 +1,53 @@
package com.mtusi.messenger.main.infrastructure.controllers.authentication
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.infrastructure.controllers.authentication.responses.SessionResponse
import com.mtusi.messenger.main.infrastructure.services.authentication.AuthenticationService
import com.mtusi.messenger.main.plugins.authentication.CREDENTIALS_AUTH
import com.mtusi.messenger.main.plugins.authentication.CredentialsPrincipal
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
import io.ktor.server.auth.principal
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.delete
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import org.koin.ktor.ext.inject
fun Routing.configureAuthenticationRouting() = route("/api/v1/auth/sessions") {
val authenticationService by inject<AuthenticationService>()
authenticate(CREDENTIALS_AUTH) {
post {
val (user) = call.principal<CredentialsPrincipal>()!!
val issued = suspendedTransaction {
authenticationService.createSession(user.id)
}
call.respond(
HttpStatusCode.Created,
SessionResponse(
token = issued.token,
expiresAt = issued.session.expiresAt,
user = user
)
)
}
}
authenticate(SESSION_AUTH) {
delete("current") {
authenticationService.revokeSession(call.currentUser.session)
call.respond(HttpStatusCode.NoContent)
}
}
}
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.controllers.authentication.responses
import com.mtusi.messenger.main.infrastructure.dto.User
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class SessionResponse(
val token: String,
val tokenType: String = "Bearer",
val expiresAt: Instant,
val user: User,
)
@@ -0,0 +1,112 @@
package com.mtusi.messenger.main.infrastructure.controllers.chat
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers._common.parameters.pageParameters
import com.mtusi.messenger.main.infrastructure.controllers.chat.requests.CreateChatRequest
import com.mtusi.messenger.main.infrastructure.models.chat.MAX_CHAT_MEMBERS
import com.mtusi.messenger.main.infrastructure.models.chat.MAX_CHAT_TITLE_LENGTH
import com.mtusi.messenger.main.infrastructure.services.chat.ChatService
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.requireNonBlankBounded
import com.mtusi.messenger.main.utils.requireUuid
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
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
import org.koin.ktor.ext.inject
fun Routing.configureChatRouting() = route("/api/v1/chats") {
val chatService by inject<ChatService>()
authenticate(SESSION_AUTH) {
post {
val actor = call.currentUser
val body = call.receive<CreateChatRequest>()
requireNonBlankBounded(
body.title,
min = 1,
max = MAX_CHAT_TITLE_LENGTH,
field = "title"
)
if (body.memberIds.isEmpty() || body.memberIds.size > MAX_CHAT_MEMBERS) {
throw ApiException(ErrorCode.INVALID_REQUEST, "member_ids size out of range")
}
val memberIds = body.memberIds.map { requireUuid(it, "member_ids") }
val result = suspendedTransaction {
chatService.create(
creatorId = actor.id,
title = body.title,
memberIds = memberIds
)
}
when (result) {
is ChatCreationResult.DuplicateMembers ->
call.respondError(ErrorCode.INVALID_REQUEST, "member_ids must be unique")
is ChatCreationResult.CreatorNotMember ->
call.respondError(ErrorCode.INVALID_REQUEST, "creator must be in member ids")
is ChatCreationResult.UnknownMembers ->
call.respondError(ErrorCode.INVALID_REQUEST, "unknown member")
is ChatCreationResult.Success ->
call.respond(HttpStatusCode.Created, result.chat)
}
}
get {
val actor = call.currentUser
val (limit, cursor) = call.pageParameters()
val result = suspendedTransaction {
chatService.findPageAccessible(
userId = actor.id,
limit = limit,
cursor = cursor
)
}
when (result) {
is ChatPageResult.InvalidCursor ->
call.respondError(ErrorCode.INVALID_REQUEST, "invalid cursor")
is ChatPageResult.Success ->
call.respond(HttpStatusCode.OK, result.page)
}
}
get("{chat_id}") {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
val chat = suspendedTransaction {
chatService.findAccessible(actor.id, chatId)
}
if (chat == null) {
call.respondError(ErrorCode.NOT_FOUND, "chat not found")
return@get
}
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,67 @@
package com.mtusi.messenger.main.infrastructure.controllers.health
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers.health.responses.HealthResponse
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.isDraining
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.koin.ktor.ext.inject
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.log
import io.ktor.server.response.respond
import io.ktor.server.routing.Routing
import io.ktor.server.routing.get
import io.ktor.server.routing.route
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
fun Routing.configureHealthRouting() = route("/health") {
get("live") {
call.respond(HttpStatusCode.OK, HealthResponse())
}
val storage by inject<ObjectStorageRepository>()
// PostgreSQL and S3 are dependencies of the synchronous path; Redis has a DB fallback.
get("ready") {
// SIGTERM received: leave the balancer's rotation while requests in flight are still being finished.
if (call.application.isDraining) {
call.respondError(ErrorCode.UNAVAILABLE, "shutting down")
return@get
}
val isDatabaseReachable = try {
suspendedTransaction {
exec("SELECT 1")
}
true
} catch (cause: Exception) {
if (cause is CancellationException) {
currentCoroutineContext().ensureActive()
}
call.application.log.warn("Readiness check failed: ${cause.message}")
false
}
if (!isDatabaseReachable) {
call.respondError(ErrorCode.UNAVAILABLE, "database unavailable")
return@get
}
if (!withContext(Dispatchers.IO) { storage.ready() }) {
call.respondError(ErrorCode.UNAVAILABLE, "object storage unavailable")
return@get
}
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,94 @@
package com.mtusi.messenger.main.infrastructure.controllers.message
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers._common.parameters.pageParameters
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
import com.mtusi.messenger.main.infrastructure.models.message.MAX_MESSAGE_TEXT_LENGTH
import com.mtusi.messenger.main.infrastructure.services.message.MessageService
import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult
import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.requireIdempotencyKey
import com.mtusi.messenger.main.utils.requireUuid
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
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
import org.koin.ktor.ext.inject
fun Routing.configureMessageRouting() = route("/api/v1/chats/{chat_id}/messages") {
val messageService by inject<MessageService>()
authenticate(SESSION_AUTH) {
post {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
val idempotencyKey = requireIdempotencyKey(call.request.headers["Idempotency-Key"])
val body = call.receive<CreateMessageRequest>()
val attachmentIds = body.attachmentIds.map { requireUuid(it, "attachment_ids") }
if (attachmentIds.size > 10 || attachmentIds.distinct().size != attachmentIds.size ||
body.text.codePointCount(0, body.text.length) > MAX_MESSAGE_TEXT_LENGTH ||
(body.text.isBlank() && attachmentIds.isEmpty())) {
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid message")
}
val result = suspendedTransaction {
messageService.send(
chatId = chatId,
senderId = actor.id,
text = body.text,
idempotencyKey = idempotencyKey,
attachmentIds = attachmentIds
)
}
when (result) {
is MessageCreationResult.ChatNotFound ->
call.respondError(ErrorCode.NOT_FOUND, "chat not found")
is MessageCreationResult.IdempotencyKeyReused ->
call.respondError(ErrorCode.CONFLICT, "Idempotency-Key was used with a different message")
is MessageCreationResult.Success ->
call.respond(HttpStatusCode.Created, result.message)
}
}
get {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
val (limit, cursor) = call.pageParameters()
val result = suspendedTransaction {
messageService.findPageByChatId(
chatId = chatId,
actorId = actor.id,
limit = limit,
cursor = cursor
)
}
when (result) {
is MessagePageResult.ChatNotFound ->
call.respondError(ErrorCode.NOT_FOUND, "chat not found")
is MessagePageResult.InvalidCursor ->
call.respondError(ErrorCode.INVALID_REQUEST, "invalid cursor")
is MessagePageResult.Success ->
call.respond(HttpStatusCode.OK, result.page)
}
}
}
}
@@ -0,0 +1,9 @@
package com.mtusi.messenger.main.infrastructure.controllers.message.requests
import kotlinx.serialization.Serializable
@Serializable
data class CreateMessageRequest(
val text: String,
val attachmentIds: List<String> = emptyList(),
)
@@ -0,0 +1,83 @@
package com.mtusi.messenger.main.infrastructure.controllers.user
import com.mtusi.messenger.main.extensions.currentUser
import com.mtusi.messenger.main.extensions.respondError
import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateUserRequest
import com.mtusi.messenger.main.infrastructure.models.user.MAX_DISPLAY_NAME_LENGTH
import com.mtusi.messenger.main.infrastructure.services.user.UserService
import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.authentication.SESSION_AUTH
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.requireNonBlankBounded
import com.mtusi.messenger.main.utils.requireUsername
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
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
import org.koin.ktor.ext.inject
private const val PASSWORD_MIN = 12
private const val PASSWORD_MAX = 128
fun Routing.configureUserRouting() = route("/api/v1/users") {
val userService by inject<UserService>()
post {
val body = call.receive<CreateUserRequest>()
requireUsername(body.username)
requireNonBlankBounded(
body.displayName,
min = 1,
max = MAX_DISPLAY_NAME_LENGTH,
field = "display_name"
)
requireNonBlankBounded(
body.password,
min = PASSWORD_MIN,
max = PASSWORD_MAX,
field = "password"
)
val result = suspendedTransaction {
userService.create(
username = body.username,
displayName = body.displayName,
password = body.password
)
}
when (result) {
is UserCreationResult.UsernameTaken ->
call.respondError(ErrorCode.CONFLICT, "username already taken")
is UserCreationResult.Success ->
call.respond(HttpStatusCode.Created, result.user)
}
}
authenticate(SESSION_AUTH) {
get("me") {
val user = suspendedTransaction {
userService.findById(call.currentUser.id)
}
if (user == null) {
call.respondError(ErrorCode.UNAUTHORIZED, "unknown user")
return@get
}
call.respond(HttpStatusCode.OK, user)
}
}
}
@@ -0,0 +1,10 @@
package com.mtusi.messenger.main.infrastructure.controllers.user.requests
import kotlinx.serialization.Serializable
@Serializable
data class CreateUserRequest(
val username: String,
val displayName: String,
val password: String,
)
@@ -0,0 +1,21 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class Attachment(
val id: SerialUUID,
val chatId: SerialUUID,
val ownerId: SerialUUID,
val filename: String,
val contentType: String,
val sizeBytes: Long,
val sha256: String,
val createdAt: Instant,
val updatedAt: Instant = createdAt,
val status: String = "ready",
val variants: List<String> = emptyList(),
val errorCode: String? = null,
)
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class Chat(
val id: SerialUUID,
val title: String,
val memberIds: List<SerialUUID>,
val createdAt: Instant,
)
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class Message(
val id: SerialUUID,
val chatId: SerialUUID,
val senderId: SerialUUID,
val text: String,
val createdAt: Instant,
val attachmentIds: List<SerialUUID> = emptyList(),
)
@@ -0,0 +1,9 @@
package com.mtusi.messenger.main.infrastructure.dto
import kotlinx.serialization.Serializable
@Serializable
data class PageResponse<T : Any>(
val items: List<T>,
val nextCursor: String?,
)
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class User(
val id: SerialUUID,
val username: String,
val displayName: String,
val createdAt: Instant,
)
@@ -0,0 +1,6 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
data class IssuedSession(
val session: Session,
val token: String,
)
@@ -0,0 +1,12 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
import java.util.UUID
import kotlin.time.Instant
data class Session(
val id: UUID,
val userId: UUID,
val tokenHash: String,
val createdAt: Instant,
val expiresAt: Instant,
)
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
import kotlin.time.Instant
data class SessionRevocation(
val tokenHash: String,
val expiresAt: Instant,
)
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.dto.authentication
import com.mtusi.messenger.main.infrastructure.dto.User
data class UserCredentials(
val user: User,
val passwordHash: String,
)
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.infrastructure.models.attachment
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
object AttachmentModel : UUIDTable("attachments") {
val chatId = reference("chat_id", ChatModel)
val ownerId = reference("owner_id", UserModel)
val filename = varchar("filename", 255)
val contentType = varchar("content_type", 32)
val sizeBytes = long("size_bytes")
val sha256 = varchar("sha256", 64)
val createdAt = timestamp("created_at")
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.infrastructure.models.attachment
import com.mtusi.messenger.main.infrastructure.models.message.MessageModel
import org.jetbrains.exposed.v1.core.Table
object MessageAttachmentModel : Table("message_attachments") {
val messageId = reference("message_id", MessageModel)
val attachmentId = reference("attachment_id", AttachmentModel)
val position = integer("position")
override val primaryKey = PrimaryKey(messageId, attachmentId)
}
@@ -0,0 +1,18 @@
package com.mtusi.messenger.main.infrastructure.models.attachment
import com.mtusi.messenger.main.utils.exposed.operations.plus
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
import org.jetbrains.exposed.v1.datetime.timestamp
object UploadJournalModel : UUIDTable("attachment_uploads") {
val expiresAt = timestamp("expires_at").defaultExpression(CurrentTimestamp + longLiteral(3600))
val abandoned = bool("abandoned").default(false)
val nextAttemptAt = timestamp("next_attempt_at").defaultExpression(CurrentTimestamp + longLiteral(3600))
init {
index("attachment_uploads_next_attempt_idx", false, nextAttemptAt)
}
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.models.authentication
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
object SessionModel : UUIDTable("sessions") {
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "sessions_user_id_fkey")
val tokenHash = varchar("token_hash", 64).uniqueIndex("sessions_token_hash_key")
val createdAt = timestamp("created_at")
val expiresAt = timestamp("expires_at")
init {
index("sessions_user_id_idx", false, userId)
}
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.infrastructure.models.authentication
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.datetime.timestamp
object SessionRevocationModel : Table("session_revocations") {
val tokenHash = varchar("token_hash", 64)
val expiresAt = timestamp("expires_at")
override val primaryKey = PrimaryKey(tokenHash, name = "session_revocations_pkey")
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.models.chat
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.Table
object ChatMemberModel : Table("chat_members") {
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_chat_id_fkey")
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "chat_members_user_id_fkey")
val position = integer("position")
override val primaryKey = PrimaryKey(chatId, userId)
init {
index("chat_members_user_id_idx", false, userId)
}
}
@@ -0,0 +1,12 @@
package com.mtusi.messenger.main.infrastructure.models.chat
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
const val MAX_CHAT_TITLE_LENGTH = 100
const val MAX_CHAT_MEMBERS = 100
object ChatModel : UUIDTable("chats") {
val title = varchar("title", MAX_CHAT_TITLE_LENGTH)
val createdAt = timestamp("created_at")
}
@@ -0,0 +1,25 @@
package com.mtusi.messenger.main.infrastructure.models.message
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.datetime.timestamp
const val MAX_IDEMPOTENCY_KEY_LENGTH = 128
object MessageIdempotencyKeyModel : Table("message_idempotency_keys") {
val userId = reference("user_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "message_idempotency_keys_user_id_fkey")
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "message_idempotency_keys_chat_id_fkey")
val key = varchar("key", MAX_IDEMPOTENCY_KEY_LENGTH)
val requestHash = varchar("request_hash", 64)
val messageId = optReference("message_id", MessageModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "message_idempotency_keys_message_id_fkey")
val createdAt = timestamp("created_at")
override val primaryKey = PrimaryKey(userId, chatId, key, name = "message_idempotency_keys_pkey")
init {
index("message_idempotency_keys_chat_id_idx", false, chatId)
index("message_idempotency_keys_message_id_idx", false, messageId)
}
}
@@ -0,0 +1,20 @@
package com.mtusi.messenger.main.infrastructure.models.message
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
const val MAX_MESSAGE_TEXT_LENGTH = 4000
object MessageModel : UUIDTable("messages") {
val chatId = reference("chat_id", ChatModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_chat_id_fkey")
val senderId = reference("sender_id", UserModel, onDelete = ReferenceOption.CASCADE, onUpdate = ReferenceOption.NO_ACTION, fkName = "messages_sender_id_fkey")
val text = varchar("text", MAX_MESSAGE_TEXT_LENGTH)
val createdAt = timestamp("created_at")
init {
index("messages_chat_id_created_at_id_idx", false, chatId, createdAt, id)
}
}
@@ -0,0 +1,14 @@
package com.mtusi.messenger.main.infrastructure.models.user
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
const val MAX_USERNAME_LENGTH = 32
const val MAX_DISPLAY_NAME_LENGTH = 100
object UserModel : UUIDTable("users") {
val username = varchar("username", MAX_USERNAME_LENGTH).uniqueIndex("users_username_key")
val displayName = varchar("display_name", MAX_DISPLAY_NAME_LENGTH)
val passwordHash = varchar("password_hash", 255)
val createdAt = timestamp("created_at")
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.repositories
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
@Module
@ComponentScan
class RepositoriesModule
@@ -0,0 +1,3 @@
package com.mtusi.messenger.main.infrastructure.repositories
interface Repository<TId, TEntity>
@@ -0,0 +1,88 @@
package com.mtusi.messenger.main.infrastructure.repositories._common
import com.mtusi.messenger.main.config.redis.RedisConfig
import com.mtusi.messenger.main.utils.resolveSecret
import io.lettuce.core.ClientOptions
import io.lettuce.core.RedisClient
import io.lettuce.core.RedisConnectionException
import io.lettuce.core.RedisURI
import io.lettuce.core.SocketOptions
import io.lettuce.core.TimeoutOptions
import io.lettuce.core.api.StatefulRedisConnection
import io.lettuce.core.api.async.RedisAsyncCommands
import io.lettuce.core.codec.StringCodec
import kotlinx.coroutines.future.await
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.koin.core.annotation.Single
import java.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
private val RECONNECT_BACKOFF = 1.seconds
/**
* Lazily connected Redis client. The application must start and serve requests without Redis, so the connection
* is opened on first use, a failed attempt is not retried for [RECONNECT_BACKOFF], and commands issued while
* disconnected fail immediately instead of queueing behind the reconnect.
*/
@Single
class RedisConnection(
config: RedisConfig
) : AutoCloseable {
private val uri = RedisURI.builder()
.withHost(config.host)
.withPort(config.port)
.withTimeout(Duration.ofMillis(config.commandTimeoutMs))
.apply {
val password = resolveSecret(config.password, config.passwordFile)
if (password != null) {
if (config.username != null) withAuthentication(config.username, password) else withPassword(password.toCharArray())
}
}
.build()
private val client = RedisClient.create().apply {
options = ClientOptions.builder()
.autoReconnect(true)
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
.timeoutOptions(TimeoutOptions.enabled(Duration.ofMillis(config.commandTimeoutMs)))
.socketOptions(SocketOptions.builder().connectTimeout(Duration.ofMillis(config.connectTimeoutMs)).build())
.build()
}
private val mutex = Mutex()
@Volatile
private var connection: StatefulRedisConnection<String, String>? = null
@Volatile
private var nextAttempt = TimeSource.Monotonic.markNow()
suspend fun commands(): RedisAsyncCommands<String, String> {
return (connection ?: connect()).async()
}
private suspend fun connect(): StatefulRedisConnection<String, String> = mutex.withLock {
connection?.let { return it }
if (nextAttempt.hasNotPassedNow()) {
throw RedisConnectionException("Redis is unavailable, next connection attempt is postponed")
}
return try {
client.connectAsync(StringCodec.UTF8, uri).await().also { connection = it }
} catch (e: Exception) {
nextAttempt = TimeSource.Monotonic.markNow() + RECONNECT_BACKOFF
throw e as? RedisConnectionException ?: RedisConnectionException("Unable to connect to Redis", e)
}
}
override fun close() {
connection?.close()
client.shutdown()
}
}
@@ -0,0 +1,20 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import java.util.UUID
interface AttachmentRepository {
fun create(attachment: Attachment)
fun findById(id: UUID): Attachment?
fun attach(
messageId: UUID,
ids: List<UUID>
)
fun idsForMessage(messageId: UUID): List<UUID>
fun idsForMessages(messageIds: List<UUID>): Map<UUID, List<UUID>>
}
@@ -0,0 +1,88 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel
import com.mtusi.messenger.main.infrastructure.models.attachment.MessageAttachmentModel
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.inList
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.SortOrder
import org.koin.core.annotation.Single
import java.util.UUID
@Single
class ExposedAttachmentRepository : AttachmentRepository {
override fun create(attachment: Attachment) {
AttachmentModel.insert {
it[id] = attachment.id
it[chatId] = attachment.chatId
it[ownerId] = attachment.ownerId
it[filename] = attachment.filename
it[contentType] = attachment.contentType
it[sizeBytes] = attachment.sizeBytes
it[sha256] = attachment.sha256
it[createdAt] = attachment.createdAt
}
}
override fun findById(
id: UUID
): Attachment? {
return AttachmentModel
.selectAll()
.where(AttachmentModel.id eq id)
.firstOrNull()
?.toAttachment()
}
override fun attach(
messageId: UUID,
ids: List<UUID>
) {
ids.forEachIndexed { index, id ->
MessageAttachmentModel.insert {
it[this.messageId] = messageId
it[attachmentId] = id
it[position] = index
}
}
}
override fun idsForMessage(
messageId: UUID
): List<UUID> {
return idsForMessages(listOf(messageId))[messageId].orEmpty()
}
override fun idsForMessages(
messageIds: List<UUID>
): Map<UUID, List<UUID>> {
if (messageIds.isEmpty()) {
return emptyMap()
}
return MessageAttachmentModel
.selectAll()
.where(MessageAttachmentModel.messageId inList messageIds)
.orderBy(MessageAttachmentModel.position to SortOrder.ASC)
.groupBy(
keySelector = { it[MessageAttachmentModel.messageId].value },
valueTransform = { it[MessageAttachmentModel.attachmentId].value }
)
}
private fun ResultRow.toAttachment() = Attachment(
id = this[AttachmentModel.id].value,
chatId = this[AttachmentModel.chatId].value,
ownerId = this[AttachmentModel.ownerId].value,
filename = this[AttachmentModel.filename],
contentType = this[AttachmentModel.contentType],
sizeBytes = this[AttachmentModel.sizeBytes],
sha256 = this[AttachmentModel.sha256],
createdAt = this[AttachmentModel.createdAt]
)
}
@@ -0,0 +1,77 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment
import com.mtusi.messenger.main.infrastructure.models.attachment.UploadJournalModel
import com.mtusi.messenger.main.utils.exposed.operations.plus
import org.jetbrains.exposed.v1.core.SortOrder
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.greater
import org.jetbrains.exposed.v1.core.inList
import org.jetbrains.exposed.v1.core.lessEq
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.core.vendors.ForUpdateOption
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
import org.jetbrains.exposed.v1.jdbc.deleteWhere
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.select
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.update
import org.koin.core.annotation.Single
import java.util.UUID
@Single
class ExposedUploadJournalRepository : UploadJournalRepository {
override fun register(
id: UUID
) {
UploadJournalModel.insert {
it[this.id] = id
}
}
override fun lockForCompletion(
id: UUID
): Boolean {
val canComplete = (UploadJournalModel.abandoned eq false) and
(UploadJournalModel.expiresAt greater CurrentTimestamp)
return UploadJournalModel
.select(canComplete)
.where(UploadJournalModel.id eq id)
.forUpdate()
.firstOrNull()
?.get(canComplete)
?: false
}
override fun complete(
id: UUID
) {
UploadJournalModel.deleteWhere {
UploadJournalModel.id eq id
}
}
override fun claimExpired(): List<UUID> {
val ids = UploadJournalModel
.selectAll()
.where(UploadJournalModel.nextAttemptAt lessEq CurrentTimestamp)
.orderBy(UploadJournalModel.nextAttemptAt to SortOrder.ASC)
.limit(100)
.forUpdate(ForUpdateOption.PostgreSQL.ForUpdate(ForUpdateOption.PostgreSQL.MODE.SKIP_LOCKED))
.map {
it[UploadJournalModel.id].value
}
if (ids.isNotEmpty()) {
UploadJournalModel.update({ UploadJournalModel.id inList ids }) {
it[abandoned] = true
it[nextAttemptAt] = CurrentTimestamp + longLiteral(60)
}
}
return ids
}
}
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment
import java.util.UUID
interface UploadJournalRepository {
fun register(id: UUID)
fun lockForCompletion(id: UUID): Boolean
fun complete(id: UUID)
fun claimExpired(): List<UUID>
}
@@ -0,0 +1,19 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment.storage
import java.io.File
import java.util.UUID
interface ObjectStorageRepository {
suspend fun put(
id: UUID,
file: File,
contentType: String
)
suspend fun get(id: UUID): ByteArray
suspend fun delete(id: UUID)
suspend fun ready(): Boolean
}
@@ -0,0 +1,116 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment.storage
import aws.sdk.kotlin.runtime.auth.credentials.StaticCredentialsProvider
import aws.sdk.kotlin.services.s3.S3Client
import aws.sdk.kotlin.services.s3.deleteObject
import aws.sdk.kotlin.services.s3.model.GetObjectRequest
import aws.sdk.kotlin.services.s3.headBucket
import aws.sdk.kotlin.services.s3.putObject
import aws.smithy.kotlin.runtime.content.asByteStream
import aws.smithy.kotlin.runtime.content.toByteArray
import aws.smithy.kotlin.runtime.net.url.Url
import com.mtusi.messenger.main.config.storage.StorageConfig
import com.mtusi.messenger.main.infrastructure.services.attachment.MAX_ATTACHMENT_BYTES
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.utils.resolveSecret
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.withTimeoutOrNull
import org.koin.core.annotation.Single
import java.io.File
import java.util.UUID
import kotlin.time.Duration.Companion.milliseconds
@Single
class S3ObjectStorageRepository(
private val config: StorageConfig
) : ObjectStorageRepository {
private val client by lazy {
S3Client {
endpointUrl = Url.parse(config.endpoint)
region = "us-east-1"
forcePathStyle = true
credentialsProvider = StaticCredentialsProvider {
accessKeyId = requireNotNull(resolveSecret(config.accessKey, config.accessKeyFile))
secretAccessKey = requireNotNull(resolveSecret(config.secretKey, config.secretKeyFile))
}
}
}
override suspend fun put(
id: UUID,
file: File,
contentType: String
) {
request {
client.putObject {
bucket = config.bucket
key = getObjectKey(id)
body = file.asByteStream()
this.contentType = contentType
contentLength = file.length()
}
}
}
override suspend fun get(
id: UUID
): ByteArray = request {
client.getObject(GetObjectRequest {
bucket = config.bucket
key = getObjectKey(id)
}) { response ->
val contentLength = requireNotNull(response.contentLength)
check(contentLength >= 1L && contentLength <= MAX_ATTACHMENT_BYTES.toLong())
val bytes = requireNotNull(response.body?.toByteArray())
check(bytes.size <= MAX_ATTACHMENT_BYTES)
bytes
}
}
override suspend fun delete(
id: UUID
) {
request {
client.deleteObject {
bucket = config.bucket
key = getObjectKey(id)
}
}
}
override suspend fun ready(): Boolean {
return try {
request {
client.headBucket {
bucket = config.bucket
}
}
true
} catch (_: ApiException) {
false
}
}
private fun getObjectKey(id: UUID) = "originals/$id"
private suspend fun <T : Any> request(block: suspend () -> T): T {
return try {
withTimeoutOrNull(8000.milliseconds) {
block()
} ?: throw ApiException(ErrorCode.UNAVAILABLE, "object storage unavailable")
} catch (cause: CancellationException) {
throw cause
} catch (_: Exception) {
throw ApiException(ErrorCode.UNAVAILABLE, "object storage unavailable")
}
}
}
@@ -0,0 +1,73 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.greater
import org.jetbrains.exposed.v1.jdbc.deleteWhere
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Instant
@Single
class ExposedSessionRepository : SessionRepository {
override fun create(
userId: UUID,
tokenHash: String,
ttl: Duration
): Session {
val createdAt = Clock.System.nowMicros()
val expiresAt = createdAt + ttl
val insertedRow = SessionModel.insert {
it[this.userId] = userId
it[this.tokenHash] = tokenHash
it[this.createdAt] = createdAt
it[this.expiresAt] = expiresAt
}
return Session(
id = insertedRow[SessionModel.id].value,
userId = userId,
tokenHash = tokenHash,
createdAt = createdAt,
expiresAt = expiresAt
)
}
override fun findActiveByTokenHash(
tokenHash: String,
now: Instant
): Session? {
return SessionModel
.selectAll()
.where((SessionModel.tokenHash eq tokenHash) and (SessionModel.expiresAt greater now))
.firstOrNull()
?.toSession()
}
override fun deleteById(
id: UUID
): Boolean {
val deletedRows = SessionModel.deleteWhere { SessionModel.id eq id }
return deletedRows > 0
}
private fun ResultRow.toSession() = Session(
id = this[SessionModel.id].value,
userId = this[SessionModel.userId].value,
tokenHash = this[SessionModel.tokenHash],
createdAt = this[SessionModel.createdAt],
expiresAt = this[SessionModel.expiresAt]
)
}
@@ -0,0 +1,26 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import java.util.UUID
import kotlin.time.Duration
import kotlin.time.Instant
interface SessionRepository : Repository<UUID, Session> {
fun create(
userId: UUID,
tokenHash: String,
ttl: Duration
): Session
fun findActiveByTokenHash(
tokenHash: String,
now: Instant
): Session?
fun deleteById(
id: UUID
): Boolean
}
@@ -0,0 +1,11 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
sealed class CachedSession {
data class Active(val session: Session) : CachedSession()
data object Revoked : CachedSession()
}
@@ -0,0 +1,87 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories._common.RedisConnection
import io.lettuce.core.SetArgs
import kotlinx.coroutines.future.await
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.koin.core.annotation.Single
import kotlin.time.Instant
private const val KEY_PREFIX = "session:"
private const val REVOKED = "revoked"
@Single
class RedisSessionCacheRepository(
private val redis: RedisConnection
) : SessionCacheRepository {
override suspend fun find(
tokenHash: String
): CachedSession? {
val value = redis.commands().get(key(tokenHash)).await() ?: return null
if (value == REVOKED) {
return CachedSession.Revoked
}
return CachedSession.Active(
Json.decodeFromString<SessionEntry>(value).toSession(tokenHash)
)
}
override suspend fun putIfAbsent(
session: Session,
cachedUntil: Instant
) {
redis.commands().set(
key(session.tokenHash),
Json.encodeToString(SessionEntry.from(session)),
SetArgs.Builder.nx().pxAt(cachedUntil.toEpochMilliseconds())
).await()
}
override suspend fun revoke(
tokenHash: String,
expiresAt: Instant
) {
redis.commands().set(
key(tokenHash),
REVOKED,
SetArgs.Builder.pxAt(expiresAt.toEpochMilliseconds())
).await()
}
private fun key(tokenHash: String) = KEY_PREFIX + tokenHash
@Serializable
private data class SessionEntry(
val id: SerialUUID,
val userId: SerialUUID,
val createdAt: Instant,
val expiresAt: Instant
) {
fun toSession(tokenHash: String) = Session(
id = id,
userId = userId,
tokenHash = tokenHash,
createdAt = createdAt,
expiresAt = expiresAt
)
companion object {
fun from(session: Session) = SessionEntry(
id = session.id,
userId = session.userId,
createdAt = session.createdAt,
expiresAt = session.expiresAt
)
}
}
}
@@ -0,0 +1,23 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.cache
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import kotlin.time.Instant
interface SessionCacheRepository : Repository<String, Session> {
suspend fun find(
tokenHash: String
): CachedSession?
suspend fun putIfAbsent(
session: Session,
cachedUntil: Instant
)
suspend fun revoke(
tokenHash: String,
expiresAt: Instant
)
}
@@ -0,0 +1,52 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation
import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionRevocationModel
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.greater
import org.jetbrains.exposed.v1.core.lessEq
import org.jetbrains.exposed.v1.jdbc.deleteWhere
import org.jetbrains.exposed.v1.jdbc.insertIgnore
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import kotlin.time.Instant
@Single
class ExposedSessionRevocationRepository : SessionRevocationRepository {
override fun add(
revocation: SessionRevocation
) {
SessionRevocationModel.insertIgnore {
it[tokenHash] = revocation.tokenHash
it[expiresAt] = revocation.expiresAt
}
}
override fun findPending(
now: Instant
): List<SessionRevocation> {
return SessionRevocationModel
.selectAll()
.where(SessionRevocationModel.expiresAt greater now)
.map {
SessionRevocation(
tokenHash = it[SessionRevocationModel.tokenHash],
expiresAt = it[SessionRevocationModel.expiresAt]
)
}
}
override fun delete(
tokenHash: String
) {
SessionRevocationModel.deleteWhere { SessionRevocationModel.tokenHash eq tokenHash }
}
override fun deleteExpired(
now: Instant
) {
SessionRevocationModel.deleteWhere { SessionRevocationModel.expiresAt lessEq now }
}
}
@@ -0,0 +1,25 @@
package com.mtusi.messenger.main.infrastructure.repositories.authentication.session.revocation
import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import kotlin.time.Instant
interface SessionRevocationRepository : Repository<String, SessionRevocation> {
fun add(
revocation: SessionRevocation
)
fun findPending(
now: Instant
): List<SessionRevocation>
fun delete(
tokenHash: String
)
fun deleteExpired(
now: Instant
)
}
@@ -0,0 +1,30 @@
package com.mtusi.messenger.main.infrastructure.repositories.chat
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import com.mtusi.messenger.main.utils.PageKey
import java.util.UUID
interface ChatRepository : Repository<UUID, Chat> {
fun create(
title: String,
memberIds: List<UUID>
): Chat
fun findById(
id: UUID
): Chat?
fun isMember(
chatId: UUID,
userId: UUID
): Boolean
fun findPageByMemberId(
userId: UUID,
after: PageKey?,
limit: Int
): List<Chat>
}
@@ -0,0 +1,134 @@
package com.mtusi.messenger.main.infrastructure.repositories.chat
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.exposed.operations.RowGreater
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.QueryParameter
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.SortOrder
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.inList
import org.jetbrains.exposed.v1.jdbc.batchInsert
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
@Single
class ExposedChatRepository : ChatRepository {
override fun create(
title: String,
memberIds: List<UUID>
): Chat {
val insertedRow = ChatModel.insert {
it[this.title] = title
it[this.createdAt] = Clock.System.nowMicros()
}
val chatId = insertedRow[ChatModel.id].value
ChatMemberModel.batchInsert(memberIds.withIndex()) { (position, userId) ->
this[ChatMemberModel.chatId] = chatId
this[ChatMemberModel.userId] = userId
this[ChatMemberModel.position] = position
}
return Chat(
id = chatId,
title = title,
memberIds = memberIds,
createdAt = insertedRow[ChatModel.createdAt]
)
}
override fun findById(
id: UUID
): Chat? {
val row = ChatModel
.selectAll()
.where(ChatModel.id eq id)
.firstOrNull()
?: return null
return row.toChat(findMemberIds(listOf(id))[id].orEmpty())
}
override fun isMember(
chatId: UUID,
userId: UUID
): Boolean {
return ChatMemberModel
.selectAll()
.where((ChatMemberModel.chatId eq chatId) and (ChatMemberModel.userId eq userId))
.empty()
.not()
}
override fun findPageByMemberId(
userId: UUID,
after: PageKey?,
limit: Int
): List<Chat> {
var condition = ChatMemberModel.userId eq userId
if (after != null) {
condition = condition and RowGreater(
left = listOf(ChatModel.createdAt, ChatModel.id),
right = listOf(
QueryParameter(after.createdAt, ChatModel.createdAt.columnType),
QueryParameter(EntityID(after.id, ChatModel), ChatModel.id.columnType)
)
)
}
val rows = ChatModel
.innerJoin(ChatMemberModel)
.selectAll()
.where(condition)
.orderBy(ChatModel.createdAt to SortOrder.ASC, ChatModel.id to SortOrder.ASC)
.limit(limit)
.toList()
val memberIds = findMemberIds(rows.map { it[ChatModel.id].value })
return rows.map {
it.toChat(memberIds[it[ChatModel.id].value].orEmpty())
}
}
private fun findMemberIds(
chatIds: List<UUID>
): Map<UUID, List<UUID>> {
if (chatIds.isEmpty()) {
return emptyMap()
}
return ChatMemberModel
.selectAll()
.where(ChatMemberModel.chatId inList chatIds)
.orderBy(ChatMemberModel.position to SortOrder.ASC)
.groupBy(
keySelector = { it[ChatMemberModel.chatId].value },
valueTransform = { it[ChatMemberModel.userId].value }
)
}
private fun ResultRow.toChat(memberIds: List<UUID>) = Chat(
id = this[ChatModel.id].value,
title = this[ChatModel.title],
memberIds = memberIds,
createdAt = this[ChatModel.createdAt]
)
}
@@ -0,0 +1,99 @@
package com.mtusi.messenger.main.infrastructure.repositories.message
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.models.message.MessageModel
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.exposed.operations.RowGreater
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.QueryParameter
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.SortOrder
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.dao.id.EntityID
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
@Single
class ExposedMessageRepository(
private val attachments: AttachmentRepository
) : MessageRepository {
override fun create(
chatId: UUID,
senderId: UUID,
text: String
): Message {
val insertedRow = MessageModel.insert {
it[this.chatId] = chatId
it[this.senderId] = senderId
it[this.text] = text
it[this.createdAt] = Clock.System.nowMicros()
}
return Message(
id = insertedRow[MessageModel.id].value,
chatId = chatId,
senderId = senderId,
text = text,
createdAt = insertedRow[MessageModel.createdAt]
)
}
override fun findById(
id: UUID
): Message? {
return MessageModel
.selectAll()
.where(MessageModel.id eq id)
.firstOrNull()
?.toMessage(attachments.idsForMessage(id))
}
override fun findPageByChatId(
chatId: UUID,
after: PageKey?,
limit: Int
): List<Message> {
var condition = MessageModel.chatId eq chatId
if (after != null) {
condition = condition and RowGreater(
left = listOf(MessageModel.createdAt, MessageModel.id),
right = listOf(
QueryParameter(after.createdAt, MessageModel.createdAt.columnType),
QueryParameter(EntityID(after.id, MessageModel), MessageModel.id.columnType)
)
)
}
val rows = MessageModel
.selectAll()
.where(condition)
.orderBy(MessageModel.createdAt to SortOrder.ASC, MessageModel.id to SortOrder.ASC)
.limit(limit)
.toList()
val attachmentIds = attachments.idsForMessages(rows.map { it[MessageModel.id].value })
return rows.map {
it.toMessage(attachmentIds[it[MessageModel.id].value].orEmpty())
}
}
private fun ResultRow.toMessage(attachmentIds: List<UUID>) = Message(
id = this[MessageModel.id].value,
chatId = this[MessageModel.chatId].value,
senderId = this[MessageModel.senderId].value,
text = this[MessageModel.text],
attachmentIds = attachmentIds,
createdAt = this[MessageModel.createdAt]
)
}
@@ -0,0 +1,26 @@
package com.mtusi.messenger.main.infrastructure.repositories.message
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import com.mtusi.messenger.main.utils.PageKey
import java.util.UUID
interface MessageRepository : Repository<UUID, Message> {
fun create(
chatId: UUID,
senderId: UUID,
text: String
): Message
fun findById(
id: UUID
): Message?
fun findPageByChatId(
chatId: UUID,
after: PageKey?,
limit: Int
): List<Message>
}
@@ -0,0 +1,83 @@
package com.mtusi.messenger.main.infrastructure.repositories.message.idempotency
import com.mtusi.messenger.main.infrastructure.models.message.MessageIdempotencyKeyModel
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.less
import org.jetbrains.exposed.v1.jdbc.deleteWhere
import org.jetbrains.exposed.v1.jdbc.insertIgnore
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.update
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Instant
@Single
class ExposedMessageIdempotencyRepository : MessageIdempotencyRepository {
override fun claim(
userId: UUID,
chatId: UUID,
key: String,
requestHash: String,
now: Instant
): Boolean {
// INSERT ... ON CONFLICT DO NOTHING
val statement = MessageIdempotencyKeyModel.insertIgnore {
it[this.userId] = userId
it[this.chatId] = chatId
it[this.key] = key
it[this.requestHash] = requestHash
it[this.createdAt] = now
}
return statement.insertedCount > 0
}
override fun find(
userId: UUID,
chatId: UUID,
key: String
): MessageIdempotencyRecord? {
return MessageIdempotencyKeyModel
.selectAll()
.where(scope(userId, chatId, key))
.firstOrNull()
?.let {
MessageIdempotencyRecord(
requestHash = it[MessageIdempotencyKeyModel.requestHash],
messageId = it[MessageIdempotencyKeyModel.messageId]?.value,
createdAt = it[MessageIdempotencyKeyModel.createdAt]
)
}
}
override fun attachMessage(
userId: UUID,
chatId: UUID,
key: String,
messageId: UUID
) {
MessageIdempotencyKeyModel.update({ scope(userId, chatId, key) }) {
it[this.messageId] = messageId
}
}
override fun deleteExpired(
userId: UUID,
chatId: UUID,
key: String,
createdBefore: Instant
) {
MessageIdempotencyKeyModel.deleteWhere {
scope(userId, chatId, key) and (MessageIdempotencyKeyModel.createdAt less createdBefore)
}
}
private fun scope(userId: UUID, chatId: UUID, key: String) =
(MessageIdempotencyKeyModel.userId eq userId) and
(MessageIdempotencyKeyModel.chatId eq chatId) and
(MessageIdempotencyKeyModel.key eq key)
}
@@ -0,0 +1,43 @@
package com.mtusi.messenger.main.infrastructure.repositories.message.idempotency
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import java.util.UUID
import kotlin.time.Instant
data class MessageIdempotencyRecord(
val requestHash: String,
val messageId: UUID?,
val createdAt: Instant,
)
interface MessageIdempotencyRepository : Repository<String, MessageIdempotencyRecord> {
fun claim(
userId: UUID,
chatId: UUID,
key: String,
requestHash: String,
now: Instant
): Boolean
fun find(
userId: UUID,
chatId: UUID,
key: String
): MessageIdempotencyRecord?
fun attachMessage(
userId: UUID,
chatId: UUID,
key: String,
messageId: UUID
)
fun deleteExpired(
userId: UUID,
chatId: UUID,
key: String,
createdBefore: Instant
)
}
@@ -0,0 +1,82 @@
package com.mtusi.messenger.main.infrastructure.repositories.user
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.dto.authentication.UserCredentials
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import com.mtusi.messenger.main.utils.nowMicros
import org.jetbrains.exposed.v1.core.ResultRow
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.inList
import org.jetbrains.exposed.v1.jdbc.insertIgnore
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
@Single
class ExposedUserRepository : UserRepository {
override fun create(
username: String,
displayName: String,
passwordHash: String
): User? {
val statement = UserModel.insertIgnore {
it[this.username] = username
it[this.displayName] = displayName
it[this.passwordHash] = passwordHash
it[this.createdAt] = Clock.System.nowMicros()
}
if (statement.insertedCount == 0) {
return null
}
return statement.resultedValues
?.singleOrNull()
?.toUser()
}
override fun findById(
id: UUID
): User? {
return UserModel
.selectAll()
.where(UserModel.id eq id)
.firstOrNull()
?.toUser()
}
override fun findCredentialsByUsername(
username: String
): UserCredentials? {
return UserModel
.selectAll()
.where(UserModel.username eq username)
.firstOrNull()
?.let {
UserCredentials(
user = it.toUser(),
passwordHash = it[UserModel.passwordHash]
)
}
}
override fun countByIds(
ids: Collection<UUID>
): Long {
return UserModel
.selectAll()
.where(UserModel.id inList ids)
.count()
}
private fun ResultRow.toUser() = User(
id = this[UserModel.id].value,
username = this[UserModel.username],
displayName = this[UserModel.displayName],
createdAt = this[UserModel.createdAt]
)
}
@@ -0,0 +1,28 @@
package com.mtusi.messenger.main.infrastructure.repositories.user
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.dto.authentication.UserCredentials
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import java.util.UUID
interface UserRepository : Repository<UUID, User> {
fun create(
username: String,
displayName: String,
passwordHash: String
): User?
fun findById(
id: UUID
): User?
fun findCredentialsByUsername(
username: String
): UserCredentials?
fun countByIds(
ids: Collection<UUID>
): Long
}
@@ -0,0 +1,8 @@
package com.mtusi.messenger.main.infrastructure.services
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
@Module
@ComponentScan
class ServicesModule
@@ -0,0 +1,34 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.infrastructure.repositories.attachment.UploadJournalRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository
import com.mtusi.messenger.main.plugins.suspendedTransaction
import kotlinx.coroutines.CancellationException
import org.koin.core.annotation.Single
@Single
class AttachmentCleanupService(
private val journalRepository: UploadJournalRepository,
private val objectStorageRepository: ObjectStorageRepository
) {
suspend fun cleanup(): Int {
val ids = suspendedTransaction {
journalRepository.claimExpired()
}
var deleted = 0
ids.forEach { id ->
try {
objectStorageRepository.delete(id)
deleted++
} catch (cause: CancellationException) {
throw cause
} catch (_: Exception) {
// The durable tombstone remains eligible for the next retry.
}
}
return deleted
}
}
@@ -0,0 +1,28 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import java.io.File
import java.util.UUID
interface AttachmentService {
suspend fun requireMember(
chatId: UUID,
actorId: UUID
)
suspend fun upload(
chatId: UUID,
actorId: UUID,
filename: String,
contentType: String,
file: File
): Attachment
suspend fun find(
id: UUID,
actorId: UUID
): Attachment
suspend fun content(attachment: Attachment): ByteArray
}
@@ -0,0 +1,94 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import com.mtusi.messenger.main.infrastructure.repositories.attachment.UploadJournalRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository
import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.computeSha256
import com.mtusi.messenger.main.utils.nowMicros
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.koin.core.annotation.Single
import java.io.File
import java.util.UUID
import kotlin.time.Clock
@Single
class DefaultAttachmentService(
private val journalRepository: UploadJournalRepository,
private val attachmentRepository: AttachmentRepository,
private val chatRepository: ChatRepository,
private val objectStorageRepository: ObjectStorageRepository,
) : AttachmentService {
override suspend fun requireMember(
chatId: UUID,
actorId: UUID
) {
if (!suspendedTransaction { chatRepository.isMember(chatId, actorId) }) {
notFound()
}
}
override suspend fun upload(
chatId: UUID,
actorId: UUID,
filename: String,
contentType: String,
file: File
): Attachment {
requireMember(chatId, actorId)
val (type, hash) = withContext(Dispatchers.IO) {
val bytes = file.readBytes()
ImageValidator.validate(bytes, contentType) to bytes.computeSha256()
}
val attachment = Attachment(
id = UUID.randomUUID(),
chatId = chatId,
ownerId = actorId,
filename = filename,
contentType = type,
sizeBytes = file.length(),
sha256 = hash,
createdAt = Clock.System.nowMicros()
)
suspendedTransaction {
journalRepository.register(attachment.id)
}
objectStorageRepository.put(attachment.id, file, type)
suspendedTransaction {
if (!journalRepository.lockForCompletion(attachment.id)) {
throw ApiException(ErrorCode.UNAVAILABLE, "upload expired")
}
attachmentRepository.create(attachment)
journalRepository.complete(attachment.id)
}
return attachment
}
override suspend fun find(
id: UUID,
actorId: UUID
): Attachment = suspendedTransaction {
val attachment = attachmentRepository.findById(id) ?: notFound()
if (!chatRepository.isMember(attachment.chatId, actorId)) {
notFound()
}
attachment
}
override suspend fun content(attachment: Attachment): ByteArray = withContext(Dispatchers.IO) {
objectStorageRepository.get(attachment.id)
}
private fun notFound(): Nothing = throw ApiException(ErrorCode.NOT_FOUND, "attachment or chat not found")
}
@@ -0,0 +1,127 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import java.nio.ByteBuffer
import java.util.zip.CRC32
import java.io.ByteArrayInputStream
import javax.imageio.ImageIO
import javax.imageio.stream.MemoryCacheImageInputStream
const val MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
private const val MAX_PIXELS = 40_000_000L
object ImageValidator {
fun validate(
bytes: ByteArray,
declaredType: String
): String {
if (bytes.size > MAX_ATTACHMENT_BYTES) {
throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "file exceeds 10 MiB")
}
try {
MemoryCacheImageInputStream(ByteArrayInputStream(bytes)).use { input ->
val readers = ImageIO.getImageReaders(input)
if (!readers.hasNext()) {
invalid()
}
val reader = readers.next()
try {
// Ignore optional compressed text metadata to bound memory usage.
reader.setInput(input, false, true)
val type = when (reader.formatName.lowercase()) {
"png" -> "image/png"
"jpeg", "jpg" -> "image/jpeg"
else -> invalid()
}
if (declaredType != type) {
invalid()
}
if (type == "image/png") {
validatePngChunks(bytes)
}
if (type == "image/jpeg" && (
bytes.size < 4 ||
bytes[bytes.lastIndex - 1] != 0xff.toByte() ||
bytes.last() != 0xd9.toByte()
)) {
invalid()
}
val width = reader.getWidth(0)
val height = reader.getHeight(0)
if (width <= 0 || height <= 0) {
invalid()
}
if (width.toLong() * height > MAX_PIXELS) {
throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "image exceeds 40 million pixels")
}
var warning = false
reader.addIIOReadWarningListener { _, _ -> warning = true }
val image = reader.read(0) ?: invalid()
image.flush()
if (warning) {
invalid()
}
return type
} finally {
reader.dispose()
}
}
} catch (cause: ApiException) {
throw cause
} catch (_: Exception) {
invalid()
}
}
private fun validatePngChunks(bytes: ByteArray) {
var offset = 8
while (offset + 12 <= bytes.size) {
val length = ByteBuffer.wrap(bytes, offset, 4).int
if (length < 0 || length.toLong() + offset + 12 > bytes.size) {
invalid()
}
val type = String(bytes, offset + 4, 4, Charsets.US_ASCII)
val crc = CRC32().apply { update(bytes, offset + 4, length + 4) }.value
val expected = ByteBuffer.wrap(bytes, offset + 8 + length, 4).int.toLong() and 0xffffffffL
if (crc != expected) {
invalid()
}
offset += length + 12
if (type == "IEND") {
if (length != 0 || offset != bytes.size) {
invalid()
}
return
}
}
invalid()
}
private fun invalid(): Nothing = throw ApiException(
ErrorCode.UNSUPPORTED_MEDIA_TYPE, "invalid PNG/JPEG or MIME mismatch"
)
}
@@ -0,0 +1,38 @@
package com.mtusi.messenger.main.infrastructure.services.authentication
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import java.util.UUID
interface AuthenticationService {
fun validateCredentials(
username: String,
password: String
): User?
fun createSession(
userId: UUID
): IssuedSession
suspend fun findSessionByToken(
token: String
): Session?
/**
* Deletes the session and confirms the revocation in the shared session cache, so that no replica accepts the
* token afterwards. Throws [com.mtusi.messenger.main.infrastructure.types.ApiException] (503) if the cache did
* not accept the tombstone in time: the logout is then not confirmed.
*/
suspend fun revokeSession(
session: Session
): Boolean
/**
* Called periodically on every replica: a revocation still waiting for its tombstone (written by any replica)
* means cached sessions cannot be trusted until it is written.
*/
suspend fun syncPendingRevocations()
}
@@ -0,0 +1,323 @@
package com.mtusi.messenger.main.infrastructure.services.authentication
import com.mtusi.messenger.main.config.authentication.AuthenticationConfig
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.dto.authentication.IssuedSession
import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocation
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.authentication.session.revocation.SessionRevocationRepository
import com.mtusi.messenger.main.infrastructure.repositories.user.UserRepository
import com.mtusi.messenger.main.infrastructure.services.hashing.HashingService
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.utils.computeSha256
import io.lettuce.core.RedisException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import org.koin.core.annotation.Single
import org.slf4j.LoggerFactory
import java.io.IOException
import java.security.SecureRandom
import java.util.Base64
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
import kotlin.time.Clock
import kotlin.time.Instant
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
private const val TOKEN_BYTES = 32
private val CACHE_RESTORE_BACKOFF = 1.seconds
private val REVOKE_RETRY_DELAY = 250.milliseconds
@Single
class DefaultAuthenticationService(
private val userRepository: UserRepository,
private val sessionRepository: SessionRepository,
private val sessionCacheRepository: SessionCacheRepository,
private val sessionRevocationRepository: SessionRevocationRepository,
private val hashingService: HashingService,
private val config: AuthenticationConfig
) : AuthenticationService {
private val logger = LoggerFactory.getLogger(DefaultAuthenticationService::class.java)
private val random = SecureRandom()
private val inFlightLookups = ConcurrentHashMap<String, CompletableDeferred<Session?>>()
private val isCacheAvailable = AtomicBoolean(true)
private val cacheFailures = AtomicLong()
@Volatile
private var trustedAtFailures = -1L
private val cacheRestoreMutex = Mutex()
@Volatile
private var nextCacheRestoreAttempt = TimeSource.Monotonic.markNow()
private val dummyPasswordHash by lazy {
hashingService.computeHash(HashingAlgorithm.Argon2id, "dummy-password-for-timing")
}
override fun validateCredentials(
username: String,
password: String
): User? {
val credentials = userRepository.findCredentialsByUsername(username)
val isPasswordValid = hashingService.validateHash(
algorithm = HashingAlgorithm.Argon2id,
input = password,
hashed = credentials?.passwordHash ?: dummyPasswordHash
)
if (credentials == null || !isPasswordValid) {
return null
}
return credentials.user
}
override fun createSession(
userId: UUID
): IssuedSession {
val token = ByteArray(TOKEN_BYTES)
.also(random::nextBytes)
.let(Base64.getUrlEncoder().withoutPadding()::encodeToString)
val session = sessionRepository.create(
userId = userId,
tokenHash = token.toByteArray().computeSha256(),
ttl = config.sessionTtlSeconds.seconds
)
return IssuedSession(
session = session,
token = token
)
}
override suspend fun findSessionByToken(
token: String
): Session? {
val tokenHash = token.toByteArray().computeSha256()
val now = Clock.System.now()
when (val cached = findCachedSession(tokenHash)) {
is CachedSession.Revoked -> return null
is CachedSession.Active -> return cached.session.takeIf { it.expiresAt > now }
null -> Unit
}
if (!config.sessionCacheSingleFlight) {
return selectSession(tokenHash, now)?.also { cacheSession(it, now) }
}
val flight = CompletableDeferred<Session?>()
inFlightLookups.putIfAbsent(tokenHash, flight)?.let { leader ->
return leader.await()
}
try {
// The query is shared with the followers, so the leader's own cancellation must not abort it.
val session = withContext(NonCancellable) {
selectSession(tokenHash, now)
}
flight.complete(session)
// Requests arriving until the cache write lands reuse this result instead of starting a new lookup.
// A logout drops the flight first (see revokeSession), so a revoked session is never handed out here.
session?.let { cacheSession(it, now) }
return session
} catch (e: Throwable) {
flight.completeExceptionally(e)
throw e
} finally {
inFlightLookups.remove(tokenHash, flight)
}
}
private suspend fun selectSession(
tokenHash: String,
now: Instant
): Session? {
return suspendedTransaction {
sessionRepository.findActiveByTokenHash(tokenHash, now)
}
}
override suspend fun revokeSession(
session: Session
): Boolean {
// The revocation is kept in PostgreSQL until its tombstone is in Redis: if Redis is unavailable now,
// the tombstone is written when the cache is trusted again (see restoreCache), even after a restart.
val isDeleted = suspendedTransaction {
sessionRevocationRepository.add(SessionRevocation(session.tokenHash, session.expiresAt))
sessionRepository.deleteById(session.id)
}
// A lookup that started before the delete must not be joined by requests arriving after the logout.
inFlightLookups.remove(session.tokenHash)
// Other replicas may hold the session in the shared cache: 204 is only allowed once the tombstone is there.
// Redis that rejects or delays writes (CLIENT PAUSE WRITE, reconnect) gets retried until the deadline.
val deadline = TimeSource.Monotonic.markNow() + config.sessionRevokeTimeoutMs.milliseconds
while (withCache { sessionCacheRepository.revoke(session.tokenHash, session.expiresAt) } == null) {
if (deadline.hasPassedNow()) {
// The row stays in session_revocations: every replica stops trusting the cache within a second
// (syncPendingRevocations) and the tombstone is written as soon as Redis accepts writes again.
throw ApiException(ErrorCode.UNAVAILABLE, "logout is not confirmed: session cache is unavailable")
}
delay(REVOKE_RETRY_DELAY)
}
// Best effort: a leftover row only costs one more tombstone write on the next restore.
runCatchingDatabase { sessionRevocationRepository.delete(session.tokenHash) }
return isDeleted
}
override suspend fun syncPendingRevocations() {
val hasPending = runCatchingDatabase {
sessionRevocationRepository.findPending(Clock.System.now()).isNotEmpty()
} ?: return
if (hasPending && trustedAtFailures == cacheFailures.get()) {
// Reuses the failure counter: an untrusted cache is bypassed until restoreCache writes the tombstones.
cacheFailures.incrementAndGet()
logger.warn("Pending session revocations found, cached sessions are not trusted until they are written")
}
if (hasPending) {
restoreCache()
}
}
private suspend fun findCachedSession(
tokenHash: String
): CachedSession? {
if (trustedAtFailures != cacheFailures.get() && !restoreCache()) {
return null
}
return withCache { sessionCacheRepository.find(tokenHash) }
}
private suspend fun restoreCache(): Boolean {
if (!cacheRestoreMutex.tryLock()) {
return false
}
try {
val failures = cacheFailures.get()
if (trustedAtFailures == failures) {
return true
}
if (nextCacheRestoreAttempt.hasNotPassedNow()) {
return false
}
nextCacheRestoreAttempt = TimeSource.Monotonic.markNow() + CACHE_RESTORE_BACKOFF
val now = Clock.System.now()
val pending = runCatchingDatabase {
sessionRevocationRepository.deleteExpired(now)
sessionRevocationRepository.findPending(now)
} ?: return false
for (revocation in pending) {
withCache { sessionCacheRepository.revoke(revocation.tokenHash, revocation.expiresAt) } ?: return false
}
if (pending.isNotEmpty()) {
runCatchingDatabase { pending.forEach { sessionRevocationRepository.delete(it.tokenHash) } }
logger.info("Wrote ${pending.size} pending session revocations to the cache")
}
// A failure while restoring changed the counter, so the cache stays untrusted.
trustedAtFailures = failures
return trustedAtFailures == cacheFailures.get()
} finally {
cacheRestoreMutex.unlock()
}
}
private suspend fun <T> runCatchingDatabase(
statement: () -> T
): T? {
return try {
suspendedTransaction { statement() }
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
logger.warn("Unable to update pending session revocations: ${e.message}")
null
}
}
private suspend fun cacheSession(
session: Session,
now: Instant
) {
withCache {
sessionCacheRepository.putIfAbsent(
session = session,
cachedUntil = minOf(session.expiresAt, now + config.sessionCacheTtlSeconds.seconds)
)
}
}
private suspend fun <T> withCache(
operation: suspend () -> T
): T? {
return try {
operation().also {
if (isCacheAvailable.compareAndSet(false, true)) {
logger.info("Session cache is available again")
}
}
} catch (e: RedisException) {
onCacheUnavailable(e)
} catch (e: IOException) {
onCacheUnavailable(e)
}
}
private fun onCacheUnavailable(
cause: Exception
): Nothing? {
cacheFailures.incrementAndGet()
if (isCacheAvailable.compareAndSet(true, false)) {
logger.warn("Session cache is unavailable, sessions are read from the database: ${cause.message}")
}
return null
}
}
@@ -0,0 +1,27 @@
package com.mtusi.messenger.main.infrastructure.services.chat
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatCreationResult
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult
import java.util.UUID
interface ChatService {
fun create(
creatorId: UUID,
title: String,
memberIds: List<UUID>
): ChatCreationResult
fun findAccessible(
userId: UUID,
chatId: UUID
): Chat?
fun findPageAccessible(
userId: UUID,
limit: Int,
cursor: String?
): ChatPageResult
}
@@ -0,0 +1,79 @@
package com.mtusi.messenger.main.infrastructure.services.chat
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.services.chat.results.ChatCreationResult
import com.mtusi.messenger.main.infrastructure.services.chat.results.ChatPageResult
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.decodeCursor
import com.mtusi.messenger.main.utils.toPage
import org.koin.core.annotation.Single
import java.util.UUID
@Single
class DefaultChatService(
private val chatRepository: ChatRepository,
private val userRepository: UserRepository
) : ChatService {
override fun create(
creatorId: UUID,
title: String,
memberIds: List<UUID>
): ChatCreationResult {
if (memberIds.toSet().size != memberIds.size) {
return ChatCreationResult.DuplicateMembers
}
if (creatorId !in memberIds) {
return ChatCreationResult.CreatorNotMember
}
if (userRepository.countByIds(memberIds) != memberIds.size.toLong()) {
return ChatCreationResult.UnknownMembers
}
val chat = chatRepository.create(
title = title,
memberIds = memberIds
)
return ChatCreationResult.Success(chat)
}
override fun findAccessible(
userId: UUID,
chatId: UUID
): Chat? {
return chatRepository.findById(chatId)
?.takeIf { userId in it.memberIds }
}
override fun findPageAccessible(
userId: UUID,
limit: Int,
cursor: String?
): ChatPageResult {
val scope = "chats:$userId"
val after = cursor?.let {
decodeCursor(it, scope) ?: return ChatPageResult.InvalidCursor
}
val page = chatRepository
.findPageByMemberId(
userId = userId,
after = after,
limit = limit + 1
)
.toPage(limit, scope) {
PageKey(it.createdAt, it.id)
}
return ChatPageResult.Success(page)
}
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.services.chat.results
import com.mtusi.messenger.main.infrastructure.dto.Chat
sealed class ChatCreationResult {
sealed class Error : ChatCreationResult()
data object DuplicateMembers : Error()
data object CreatorNotMember : Error()
data object UnknownMembers : Error()
data class Success(
val chat: Chat
) : ChatCreationResult()
}
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.infrastructure.services.chat.results
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
sealed class ChatPageResult {
sealed class Error : ChatPageResult()
data object InvalidCursor : Error()
data class Success(
val page: PageResponse<Chat>
) : ChatPageResult()
}
@@ -0,0 +1,123 @@
package com.mtusi.messenger.main.infrastructure.services.hashing
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
import org.bouncycastle.crypto.generators.Argon2BytesGenerator
import org.bouncycastle.crypto.params.Argon2Parameters
import org.koin.core.annotation.Single
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.Base64
// TODO: Move to config later
private const val ARGON2_MEMORY_KIB = 19 * 1024
private const val ARGON2_ITERATIONS = 2
private const val ARGON2_PARALLELISM = 1
private const val ARGON2_SALT_LENGTH = 16
private const val ARGON2_HASH_LENGTH = 32
@Single
class DefaultHashingService : HashingService {
private val random = SecureRandom()
private val encoder = Base64.getEncoder().withoutPadding()
private val decoder = Base64.getDecoder()
override fun computeHash(
algorithm: HashingAlgorithm,
input: String
): String {
return when (algorithm) {
HashingAlgorithm.Argon2id -> computeHashArgon2id(input)
}
}
private fun computeHashArgon2id(input: String): String {
val salt = ByteArray(ARGON2_SALT_LENGTH).also(random::nextBytes)
val hash = argon2id(
input = input,
salt = salt,
memoryKib = ARGON2_MEMORY_KIB,
iterations = ARGON2_ITERATIONS,
parallelism = ARGON2_PARALLELISM,
length = ARGON2_HASH_LENGTH
)
return "\$argon2id\$v=19\$m=$ARGON2_MEMORY_KIB,t=$ARGON2_ITERATIONS,p=$ARGON2_PARALLELISM" +
"\$${encoder.encodeToString(salt)}\$${encoder.encodeToString(hash)}"
}
override fun validateHash(
algorithm: HashingAlgorithm,
input: String,
hashed: String
): Boolean {
return when (algorithm) {
HashingAlgorithm.Argon2id -> validateHashArgon2id(input, hashed)
}
}
private fun validateHashArgon2id(
input: String,
hashed: String
): Boolean {
return try {
val parts = hashed.split('$')
if (parts.size != 6 || parts[1] != "argon2id" || parts[2] != "v=19") {
return false
}
val parameters = parts[3]
.split(',')
.associate {
val (key, value) = it.split('=')
key to value.toInt()
}
val salt = decoder.decode(parts[4])
val expected = decoder.decode(parts[5])
val actual = argon2id(
input = input,
salt = salt,
memoryKib = parameters.getValue("m"),
iterations = parameters.getValue("t"),
parallelism = parameters.getValue("p"),
length = expected.size
)
MessageDigest.isEqual(expected, actual)
} catch (_: Exception) {
false
}
}
private fun argon2id(
input: String,
salt: ByteArray,
memoryKib: Int,
iterations: Int,
parallelism: Int,
length: Int
): ByteArray {
val parameters = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withMemoryAsKB(memoryKib)
.withIterations(iterations)
.withParallelism(parallelism)
.withSalt(salt)
.build()
val generator = Argon2BytesGenerator().apply {
init(parameters)
}
return ByteArray(length).also {
generator.generateBytes(input.toByteArray(Charsets.UTF_8), it)
}
}
}
@@ -0,0 +1,18 @@
package com.mtusi.messenger.main.infrastructure.services.hashing
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
interface HashingService {
fun computeHash(
algorithm: HashingAlgorithm,
input: String
): String
fun validateHash(
algorithm: HashingAlgorithm,
input: String,
hashed: String
): Boolean
}
@@ -0,0 +1,5 @@
package com.mtusi.messenger.main.infrastructure.services.hashing.types
sealed class HashingAlgorithm {
data object Argon2id : HashingAlgorithm()
}
@@ -0,0 +1,136 @@
package com.mtusi.messenger.main.infrastructure.services.message
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.config.message.MessageConfig
import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository
import com.mtusi.messenger.main.infrastructure.repositories.message.MessageRepository
import com.mtusi.messenger.main.infrastructure.repositories.message.idempotency.MessageIdempotencyRepository
import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult
import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.computeSha256
import com.mtusi.messenger.main.utils.decodeCursor
import com.mtusi.messenger.main.utils.nowMicros
import com.mtusi.messenger.main.utils.toPage
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Clock
import kotlin.time.Duration.Companion.seconds
// One attempt to claim a free key, plus one more if the stored key had expired and was removed
private const val CLAIM_ATTEMPTS = 2
@Single
class DefaultMessageService(
private val chatRepository: ChatRepository,
private val messageRepository: MessageRepository,
private val idempotencyRepository: MessageIdempotencyRepository,
private val attachments: AttachmentRepository,
private val config: MessageConfig
) : MessageService {
override fun send(
chatId: UUID,
senderId: UUID,
text: String,
idempotencyKey: String,
attachmentIds: List<UUID>
): MessageCreationResult {
// Access is checked on every retry too: a replay must not outlive the membership.
if (!chatRepository.isMember(chatId, senderId)) {
return MessageCreationResult.ChatNotFound
}
attachmentIds.forEach { id ->
if (attachments.findById(id)?.chatId != chatId)
throw ApiException(
ErrorCode.NOT_FOUND, "attachment not found")
}
val requestHash = (text + if (attachmentIds.isEmpty()) "" else "\u0000attachments:" + attachmentIds.joinToString(","))
.toByteArray().computeSha256()
val now = Clock.System.nowMicros()
repeat(CLAIM_ATTEMPTS) {
if (idempotencyRepository.claim(senderId, chatId, idempotencyKey, requestHash, now)) {
val message = messageRepository.create(
chatId = chatId,
senderId = senderId,
text = text
)
attachments.attach(message.id, attachmentIds)
idempotencyRepository.attachMessage(senderId, chatId, idempotencyKey, message.id)
return MessageCreationResult.Success(message.copy(attachmentIds = attachmentIds))
}
// The key is taken by a committed transaction (claim waits for an uncommitted one).
val record = idempotencyRepository.find(senderId, chatId, idempotencyKey)
?: return@repeat
val expiredBefore = now - config.idempotencyTtlSeconds.seconds
if (record.createdAt < expiredBefore) {
idempotencyRepository.deleteExpired(senderId, chatId, idempotencyKey, createdBefore = expiredBefore)
return@repeat
}
if (record.requestHash != requestHash) {
return MessageCreationResult.IdempotencyKeyReused
}
val messageId = checkNotNull(record.messageId) {
"committed idempotency key without a message"
}
val original = checkNotNull(messageRepository.findById(messageId)) {
"message of an idempotency key is missing"
}
if (original.text != text || original.attachmentIds != attachmentIds) {
return MessageCreationResult.IdempotencyKeyReused
}
return MessageCreationResult.Success(original)
}
error("Idempotency key could not be claimed")
}
override fun findPageByChatId(
chatId: UUID,
actorId: UUID,
limit: Int,
cursor: String?
): MessagePageResult {
if (!chatRepository.isMember(chatId, actorId)) {
return MessagePageResult.ChatNotFound
}
val scope = "messages:$chatId"
val after = cursor?.let {
decodeCursor(it, scope) ?: return MessagePageResult.InvalidCursor
}
val page = messageRepository
.findPageByChatId(
chatId = chatId,
after = after,
limit = limit + 1
)
.toPage(limit, scope) {
PageKey(it.createdAt, it.id)
}
return MessagePageResult.Success(page)
}
}
@@ -0,0 +1,24 @@
package com.mtusi.messenger.main.infrastructure.services.message
import com.mtusi.messenger.main.infrastructure.services.message.results.MessageCreationResult
import com.mtusi.messenger.main.infrastructure.services.message.results.MessagePageResult
import java.util.UUID
interface MessageService {
fun send(
chatId: UUID,
senderId: UUID,
text: String,
idempotencyKey: String,
attachmentIds: List<UUID> = emptyList()
): MessageCreationResult
fun findPageByChatId(
chatId: UUID,
actorId: UUID,
limit: Int,
cursor: String?
): MessagePageResult
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.services.message.results
import com.mtusi.messenger.main.infrastructure.dto.Message
sealed class MessageCreationResult {
sealed class Error : MessageCreationResult()
data object ChatNotFound : Error()
data object IdempotencyKeyReused : Error()
data class Success(
val message: Message
) : MessageCreationResult()
}
@@ -0,0 +1,17 @@
package com.mtusi.messenger.main.infrastructure.services.message.results
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
sealed class MessagePageResult {
sealed class Error : MessagePageResult()
data object ChatNotFound : Error()
data object InvalidCursor : Error()
data class Success(
val page: PageResponse<Message>
) : MessagePageResult()
}
@@ -0,0 +1,43 @@
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.services.hashing.HashingService
import com.mtusi.messenger.main.infrastructure.services.hashing.types.HashingAlgorithm
import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult
import org.koin.core.annotation.Single
import java.util.UUID
@Single
class DefaultUserService(
private val userRepository: UserRepository,
private val hashingService: HashingService
) : UserService {
override fun create(
username: String,
displayName: String,
password: String
): UserCreationResult {
val passwordHash = hashingService.computeHash(
algorithm = HashingAlgorithm.Argon2id,
input = password
)
val user = userRepository.create(
username = username,
displayName = displayName,
passwordHash = passwordHash
) ?: return UserCreationResult.UsernameTaken
return UserCreationResult.Success(user)
}
override fun findById(
id: UUID
): User? {
return userRepository.findById(id)
}
}
@@ -0,0 +1,19 @@
package com.mtusi.messenger.main.infrastructure.services.user
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.infrastructure.services.user.results.UserCreationResult
import java.util.UUID
interface UserService {
fun create(
username: String,
displayName: String,
password: String
): UserCreationResult
fun findById(
id: UUID
): User?
}
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.infrastructure.services.user.results
import com.mtusi.messenger.main.infrastructure.dto.User
sealed class UserCreationResult {
sealed class Error : UserCreationResult()
data object UsernameTaken : Error()
data class Success(
val user: User
) : UserCreationResult()
}
@@ -0,0 +1,3 @@
package com.mtusi.messenger.main.infrastructure.types
class ApiException(val code: ErrorCode, message: String) : RuntimeException(message)

Some files were not shown because too many files have changed in this diff Show More