Completed for a grade of three

This commit is contained in:
2026-10-23 14:11:11 +03:00
parent a3dbcd6ba4
commit 92c2fdc254
54 changed files with 1221 additions and 92 deletions
@@ -3,17 +3,26 @@ package com.mtusi.messenger.main
import com.mtusi.messenger.main.plugins.authentication.configureAuthentication
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.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.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>): Unit = EngineMain.main(args)
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() {
@@ -23,6 +32,8 @@ fun Application.module() {
configureContentNegotiation()
configureDefaultHeaders()
configureInstanceId()
configureCors()
configureRequestId()
configureCallLogging()
configureStatusPages()
@@ -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,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
@@ -14,6 +14,8 @@ interface DatabaseConfig {
val connectionTimeoutMs: Long
val statementTimeoutMs: Long
val migrateOnStart: Boolean
val jdbcConnectionUrl: String
get() = "jdbc:postgresql://$host:$port/$name"
@@ -12,5 +12,6 @@ data class SerialDatabaseConfig(
override val passwordFile: String? = null,
override val maxPoolSize: Int,
override val connectionTimeoutMs: Long,
override val statementTimeoutMs: 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
@@ -11,6 +11,7 @@ import com.mtusi.messenger.main.infrastructure.services.message.results.MessageP
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.requireNonBlankBounded
import com.mtusi.messenger.main.utils.requireUuid
import io.ktor.http.HttpStatusCode
@@ -33,6 +34,7 @@ fun Routing.configureMessageRouting() = route("/api/v1/chats/{chat_id}/messages"
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>()
requireNonBlankBounded(
@@ -46,13 +48,16 @@ fun Routing.configureMessageRouting() = route("/api/v1/chats/{chat_id}/messages"
messageService.send(
chatId = chatId,
senderId = actor.id,
text = body.text
text = body.text,
idempotencyKey = idempotencyKey
)
}
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)
}
@@ -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)
}
}
@@ -4,28 +4,17 @@ import com.mtusi.messenger.main.infrastructure.dto.authentication.Session
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import kotlin.time.Instant
/**
* Cache-aside copy of [com.mtusi.messenger.main.infrastructure.repositories.authentication.session.SessionRepository].
* PostgreSQL stays the source of truth: losing every key only costs a database lookup.
*/
interface SessionCacheRepository : Repository<String, Session> {
suspend fun find(
tokenHash: String
): CachedSession?
/**
* Stores the session until [cachedUntil] unless the key already exists, so a lookup racing with a logout
* cannot overwrite the tombstone written by [revoke].
*/
suspend fun putIfAbsent(
session: Session,
cachedUntil: Instant
)
/**
* Replaces the entry with a tombstone that lives until [expiresAt], when the session would have expired.
*/
suspend fun revoke(
tokenHash: String,
expiresAt: Instant
@@ -4,18 +4,12 @@ import com.mtusi.messenger.main.infrastructure.dto.authentication.SessionRevocat
import com.mtusi.messenger.main.infrastructure.repositories.Repository
import kotlin.time.Instant
/**
* Logouts that still have to be written to the session cache as tombstones (outbox).
*/
interface SessionRevocationRepository : Repository<String, SessionRevocation> {
fun add(
revocation: SessionRevocation
)
/**
* Revocations of sessions that have not expired yet: an expired session is rejected even if its copy is cached.
*/
fun findPending(
now: Instant
): List<SessionRevocation>
@@ -21,9 +21,6 @@ interface ChatRepository : Repository<UUID, Chat> {
userId: UUID
): Boolean
/**
* Chats of [userId] ordered by `(created_at, id)`, strictly after [after].
*/
fun findPageByMemberId(
userId: UUID,
after: PageKey?,
@@ -42,6 +42,16 @@ class ExposedMessageRepository : MessageRepository {
)
}
override fun findById(
id: UUID
): Message? {
return MessageModel
.selectAll()
.where(MessageModel.id eq id)
.firstOrNull()
?.toMessage()
}
override fun findPageByChatId(
chatId: UUID,
after: PageKey?,
@@ -13,6 +13,10 @@ interface MessageRepository : Repository<UUID, Message> {
text: String
): Message
fun findById(
id: UUID
): Message?
fun findPageByChatId(
chatId: UUID,
after: PageKey?,
@@ -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
)
}
@@ -16,17 +16,10 @@ interface AuthenticationService {
userId: UUID
): IssuedSession
/**
* Opens its own transaction only on a cache miss, so it must not be called inside one.
*/
suspend fun findSessionByToken(
token: String
): Session?
/**
* Deletes the session in PostgreSQL, then replaces its cached copy with a tombstone. Without Redis only the
* database is updated: a copy cached before the outage can then live for at most the cache TTL.
*/
suspend fun revokeSession(
session: Session
): Boolean
@@ -52,22 +52,10 @@ class DefaultAuthenticationService(
private val random = SecureRandom()
/**
* Database lookups currently running per token hash. Concurrent cache misses for one token wait for the
* lookup already in flight instead of each sending their own query (cache stampede protection).
*/
private val inFlightLookups = ConcurrentHashMap<String, CompletableDeferred<Session?>>()
/**
* Only availability changes are logged: with Redis down every request would otherwise add a warning.
*/
private val isCacheAvailable = AtomicBoolean(true)
/**
* Number of failed cache operations. A failure may have lost a logout tombstone, so the cache is trusted only
* after the pending revocations were written to it with no failure since: [trustedAtFailures] equals this counter.
* A fresh process starts untrusted, as the previous one may have stopped with revocations still pending.
*/
private val cacheFailures = AtomicLong()
@Volatile
@@ -206,11 +194,6 @@ class DefaultAuthenticationService(
return withCache { sessionCacheRepository.find(tokenHash) }
}
/**
* Writes the tombstones of logouts that happened while Redis was unavailable. Until that succeeds the cache
* is bypassed: a copy cached before the outage could otherwise outlive the logout. One request restores,
* the others go to the database meanwhile; a failed attempt is repeated after [CACHE_RESTORE_BACKOFF].
*/
private suspend fun restoreCache(): Boolean {
if (!cacheRestoreMutex.tryLock()) {
@@ -277,11 +260,6 @@ class DefaultAuthenticationService(
}
}
/**
* Runs a cache operation, treating an unavailable Redis as a miss: the database stays the source of truth.
* A command already written when Redis drops the connection fails with the raw [IOException] (connection
* reset), not with a [RedisException]; it means the same.
*/
private suspend fun <T> withCache(
operation: suspend () -> T
): T? {
@@ -1,38 +1,85 @@
package com.mtusi.messenger.main.infrastructure.services.message
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 messageRepository: MessageRepository,
private val idempotencyRepository: MessageIdempotencyRepository,
private val config: MessageConfig
) : MessageService {
override fun send(
chatId: UUID,
senderId: UUID,
text: String
text: String,
idempotencyKey: String
): MessageCreationResult {
// Access is checked on every retry too: a replay must not outlive the membership.
if (!chatRepository.isMember(chatId, senderId)) {
return MessageCreationResult.ChatNotFound
}
val message = messageRepository.create(
chatId = chatId,
senderId = senderId,
text = text
)
// The body has a single field, so its hash is the hash of the text.
val requestHash = text.toByteArray().computeSha256()
val now = Clock.System.nowMicros()
return MessageCreationResult.Success(message)
repeat(CLAIM_ATTEMPTS) {
if (idempotencyRepository.claim(senderId, chatId, idempotencyKey, requestHash, now)) {
val message = messageRepository.create(
chatId = chatId,
senderId = senderId,
text = text
)
idempotencyRepository.attachMessage(senderId, chatId, idempotencyKey, message.id)
return MessageCreationResult.Success(message)
}
// 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" }
return MessageCreationResult.Success(
checkNotNull(messageRepository.findById(messageId)) { "message of an idempotency key is missing" }
)
}
error("Idempotency key could not be claimed")
}
override fun findPageByChatId(
@@ -9,7 +9,8 @@ interface MessageService {
fun send(
chatId: UUID,
senderId: UUID,
text: String
text: String,
idempotencyKey: String
): MessageCreationResult
fun findPageByChatId(
@@ -8,6 +8,8 @@ sealed class MessageCreationResult {
data object ChatNotFound : Error()
data object IdempotencyKeyReused : Error()
data class Success(
val message: Message
) : MessageCreationResult()
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.config.cors.CorsConfig
import com.mtusi.messenger.main.config.cors.configure
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.cors.routing.CORS
import org.koin.ktor.ext.inject
fun Application.configureCors() = install(CORS) {
val config by this@configureCors.inject<CorsConfig>()
configure(config)
}
@@ -6,6 +6,7 @@ import com.mtusi.messenger.main.infrastructure.models.authentication.SessionMode
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionRevocationModel
import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
import com.mtusi.messenger.main.infrastructure.models.chat.ChatModel
import com.mtusi.messenger.main.infrastructure.models.message.MessageIdempotencyKeyModel
import com.mtusi.messenger.main.infrastructure.models.message.MessageModel
import com.mtusi.messenger.main.infrastructure.models.user.UserModel
import com.mtusi.messenger.main.utils.resolveSecret
@@ -46,7 +47,11 @@ fun Application.configureDatabase() {
defaultMaxAttempts = 1
}
)
applyDatabaseMigrations(dataSource)
if (config.migrateOnStart) {
applyDatabaseMigrations(dataSource)
} else {
validateDatabaseMigrations(dataSource)
}
monitor.subscribe(ApplicationStopped) {
dataSource.close()
@@ -69,18 +74,38 @@ private fun DatabaseConfig.createDataSource(): HikariDataSource {
)
}
private fun flyway(dataSource: DataSource) = Flyway.configure()
.dataSource(dataSource)
.locations("classpath:migrations")
.load()
fun applyDatabaseMigrations(
dataSource: DataSource
) {
val flyway = Flyway.configure()
.dataSource(dataSource)
.locations("classpath:migrations")
.load()
val flyway = flyway(dataSource)
flyway.migrate()
flyway.validate()
}
/**
* Fails if a migration is pending or differs from the applied one, so a replica never serves an outdated schema.
*/
fun validateDatabaseMigrations(
dataSource: DataSource
) {
flyway(dataSource).validate()
}
/**
* Entry point of `java -jar messenger.jar migrate`: applies the migrations once and exits.
* Uses the `database` section of application.conf, environment variables included.
*/
fun migrateDatabase() {
val config = HoconApplicationConfig(ConfigFactory.load())
.property("database")
.getAs<SerialDatabaseConfig>()
config.createDataSource().use(::applyDatabaseMigrations)
}
fun main(args: Array<out String>) {
@@ -96,6 +121,7 @@ private fun generateMigration(description: String) {
ChatModel,
ChatMemberModel,
MessageModel,
MessageIdempotencyKeyModel,
SessionModel,
SessionRevocationModel
)
@@ -0,0 +1,28 @@
package com.mtusi.messenger.main.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.createApplicationPlugin
import io.ktor.server.application.install
import io.ktor.server.application.log
import java.util.UUID
/**
* Identifies the replica that produced the response. Stable for the life of the process: `INSTANCE_ID` if set,
* otherwise the container hostname (Docker sets it to the short container id), otherwise a random alias.
*/
fun Application.configureInstanceId() {
val instanceId = environment.config.propertyOrNull("instance.id")?.getString()?.takeIf { it.isNotBlank() }
?: System.getenv("HOSTNAME")?.takeIf { it.isNotBlank() }
?: UUID.randomUUID().toString().take(12)
log.info("X-Instance-Id of this replica: $instanceId")
install(
createApplicationPlugin("InstanceId") {
onCall { call ->
call.response.headers.append("X-Instance-Id", instanceId, safeOnly = false)
}
}
)
}
@@ -10,9 +10,6 @@ import kotlin.time.Instant
private val json = Json { ignoreUnknownKeys = false }
/**
* Position in a `(created_at, id)` ordered list: the next page starts strictly after it.
*/
data class PageKey(
val createdAt: Instant,
val id: UUID,
@@ -30,9 +27,6 @@ fun encodeCursor(scope: String, key: PageKey): String {
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.toByteArray(Charsets.UTF_8))
}
/**
* @return page key, or null if the cursor is malformed or was issued for another resource
*/
fun decodeCursor(raw: String, expectedScope: String): PageKey? {
val cursor = try {
val bytes = Base64.getUrlDecoder().decode(raw)
@@ -48,9 +42,6 @@ fun decodeCursor(raw: String, expectedScope: String): PageKey? {
return PageKey(cursor.createdAt, cursor.id)
}
/**
* Builds a page from `limit + 1` rows fetched after the cursor: the extra row only signals that more data exists.
*/
fun <T : Any> List<T>.toPage(
limit: Int,
scope: String,
@@ -2,9 +2,6 @@ package com.mtusi.messenger.main.utils
import java.io.File
/**
* Secrets come either inline (local development) or as a mounted file (Docker secrets), the inline value wins.
*/
fun resolveSecret(
value: String?,
file: String?
@@ -5,10 +5,6 @@ import kotlin.time.Instant
private const val NANOS_PER_MICRO = 1_000
/**
* Current time truncated to microseconds: PostgreSQL timestamptz keeps exactly this precision,
* so the value returned to the client equals the one read back from the database.
*/
fun Clock.nowMicros(): Instant {
val now = now()
return Instant.fromEpochSeconds(
@@ -6,6 +6,8 @@ import java.util.UUID
private val USERNAME = Regex("^[a-z0-9_]{3,32}$")
private val IDEMPOTENCY_KEY = Regex("^[A-Za-z0-9._:-]{1,128}$")
private val UUID_REGEX = Regex(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
)
@@ -28,6 +30,13 @@ fun requireNonBlankBounded(value: String, min: Int, max: Int, field: String) {
}
}
fun requireIdempotencyKey(value: String?): String {
if (value == null || !IDEMPOTENCY_KEY.matches(value)) {
throw ApiException(ErrorCode.INVALID_REQUEST, "missing or invalid Idempotency-Key")
}
return value
}
fun requireUuid(value: String?, field: String): UUID {
if (value == null || !UUID_REGEX.matches(value)) {
throw ApiException(ErrorCode.INVALID_REQUEST, "invalid $field")
+36
View File
@@ -28,6 +28,9 @@ database {
maxPoolSize = ${?DB_MAX_POOL_SIZE}
connectionTimeoutMs = 2000
statementTimeoutMs = 5000
# Replicas run with false: compose applies migrations once in the `migrate` service.
migrateOnStart = true
migrateOnStart = ${?DB_MIGRATE_ON_START}
}
redis {
@@ -41,6 +44,39 @@ redis {
commandTimeoutMs = 500
}
cors {
# Defaults to false
#allowAnyHost = true
# Swagger UI sends "Try it out" to the contract server http://localhost:8080; pages opened elsewhere need these.
allowedHosts = [
{ host = "localhost:8080", schemes = ["http"] }
{ host = "localhost:8081", schemes = ["http"] }
{ host = "127.0.0.1:8080", schemes = ["http"] }
{ host = "127.0.0.1:8081", schemes = ["http"] }
]
# Defaults to true
#allowAnyMethod = true
#allowedMethods = [GET, POST, PATCH, PUT, DELETE, OPTIONS]
allowAnyHeader = true
#allowedHeaders = []
exposedHeaders = [X-Request-Id, X-Instance-Id, WWW-Authenticate]
# Browsers send Origin on same-origin POST too, e.g. Swagger UI served by the API itself.
allowSameOrigin = true
}
instance {
id = ${?INSTANCE_ID}
}
messages {
idempotencyTtlSeconds = 86400
idempotencyTtlSeconds = ${?IDEMPOTENCY_TTL_SECONDS}
}
authentication {
realm = "messenger"
sessionTtlSeconds = 3600
@@ -0,0 +1,19 @@
-- Idempotency-Key of POST /chats/{chat_id}/messages. Scope: user + chat (method and path are fixed) + key.
-- The row is inserted in the same transaction as the message, so a key exists only together with its message.
-- message_id is NULL only inside that transaction: the key is claimed first, the message is written next.
CREATE TABLE message_idempotency_keys (
user_id uuid NOT NULL,
chat_id uuid NOT NULL,
key varchar(128) NOT NULL,
request_hash varchar(64) NOT NULL,
message_id uuid NULL,
created_at timestamptz NOT NULL,
CONSTRAINT message_idempotency_keys_pkey PRIMARY KEY (user_id, chat_id, key),
CONSTRAINT message_idempotency_keys_user_id_fkey FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT message_idempotency_keys_chat_id_fkey FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
CONSTRAINT message_idempotency_keys_message_id_fkey FOREIGN KEY (message_id) REFERENCES messages (id) ON DELETE CASCADE
);
-- Foreign keys are not indexed automatically; the cascades from chats and messages need these.
CREATE INDEX message_idempotency_keys_chat_id_idx ON message_idempotency_keys (chat_id);
CREATE INDEX message_idempotency_keys_message_id_idx ON message_idempotency_keys (message_id);
@@ -5,6 +5,7 @@ import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
import com.mtusi.messenger.main.support.auth
import com.mtusi.messenger.main.support.createChat
import com.mtusi.messenger.main.support.idempotencyKey
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import io.ktor.client.call.body
@@ -37,6 +38,7 @@ class MessageConcurrencyTest {
repeat(perWorker) { i ->
val response = client.post("/api/v1/chats/${chat.id}/messages") {
auth(alice)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = "w$w-i$i"))
}
@@ -6,6 +6,7 @@ import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
import com.mtusi.messenger.main.support.auth
import com.mtusi.messenger.main.support.createChat
import com.mtusi.messenger.main.support.idempotencyKey
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import io.ktor.client.call.body
@@ -29,6 +30,7 @@ class MessageControllerTest {
val response = client.post("/api/v1/chats/${chat.id}/messages") {
auth(alice)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = ""))
}
@@ -45,6 +47,7 @@ class MessageControllerTest {
val response = client.post("/api/v1/chats/${chat.id}/messages") {
auth(bob)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = "hi"))
}
@@ -75,6 +78,7 @@ class MessageControllerTest {
repeat(total) { i ->
val r = client.post("/api/v1/chats/${chat.id}/messages") {
auth(alice)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = "m$i"))
}
@@ -115,6 +119,7 @@ class MessageControllerTest {
repeat(20) { i ->
client.post("/api/v1/chats/${chat.id}/messages") {
auth(alice)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = "m$i"))
}
@@ -164,6 +169,7 @@ class MessageControllerTest {
repeat(2) { i ->
client.post("/api/v1/chats/${chatA.id}/messages") {
auth(alice)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = "a$i"))
}
@@ -0,0 +1,157 @@
package com.mtusi.messenger.main.infrastructure.controllers.message
import com.mtusi.messenger.main.extensions.ErrorBody
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.dto.PageResponse
import com.mtusi.messenger.main.support.TestUser
import com.mtusi.messenger.main.support.auth
import com.mtusi.messenger.main.support.createChat
import com.mtusi.messenger.main.support.idempotencyKey
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.util.UUID
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
class MessageIdempotencyTest {
private suspend fun HttpClient.send(user: TestUser, chat: Chat, text: String, key: String?): HttpResponse {
return post("/api/v1/chats/${chat.id}/messages") {
auth(user)
if (key != null) {
idempotencyKey(key)
}
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = text))
}
}
private suspend fun HttpClient.history(user: TestUser, chat: Chat): List<Message> {
return get("/api/v1/chats/${chat.id}/messages?limit=100") { auth(user) }.body<PageResponse<Message>>().items
}
@Test
fun `retry with the same key and body returns the original message`() = runApp { client ->
val alice = client.register("alice")
val chat = client.createChat(alice, "retry", listOf(alice.id))
val key = UUID.randomUUID().toString()
val first = client.send(alice, chat, "hello", key)
val retry = client.send(alice, chat, "hello", key)
assertEquals(HttpStatusCode.Created, first.status)
assertEquals(HttpStatusCode.Created, retry.status)
assertEquals(first.body<Message>(), retry.body<Message>())
assertEquals(1, client.history(alice, chat).size)
}
@Test
fun `same key with another body is a conflict`() = runApp { client ->
val alice = client.register("alice")
val chat = client.createChat(alice, "conflict", listOf(alice.id))
val key = UUID.randomUUID().toString()
client.send(alice, chat, "first", key)
val response = client.send(alice, chat, "second", key)
assertEquals(HttpStatusCode.Conflict, response.status)
assertEquals("conflict", response.body<ErrorBody>().error.code)
assertEquals(listOf("first"), client.history(alice, chat).map { it.text })
}
@Test
fun `missing or malformed key is rejected before anything is written`() = runApp { client ->
val alice = client.register("alice")
val chat = client.createChat(alice, "keys", listOf(alice.id))
for (key in listOf(null, "", "has space", "кириллица", "a".repeat(129))) {
val response = client.send(alice, chat, "text", key)
assertEquals(HttpStatusCode.BadRequest, response.status, "key: $key")
assertEquals("invalid_request", response.body<ErrorBody>().error.code)
}
assertEquals(HttpStatusCode.Created, client.send(alice, chat, "ok", "A-z_0.9:" + "x".repeat(120)).status)
assertEquals(1, client.history(alice, chat).size)
}
@Test
fun `key scope is user and chat`() = runApp { client ->
val alice = client.register("alice")
val bob = client.register("bob")
val first = client.createChat(alice, "one", listOf(alice.id, bob.id))
val second = client.createChat(alice, "two", listOf(alice.id, bob.id))
val key = UUID.randomUUID().toString()
val ids = listOf(
client.send(alice, first, "same", key),
client.send(bob, first, "same", key),
client.send(alice, second, "same", key)
).map {
assertEquals(HttpStatusCode.Created, it.status)
it.body<Message>().id
}
assertEquals(3, ids.toSet().size)
}
@Test
fun `retry by a former outsider is still checked for access`() = runApp { client ->
val alice = client.register("alice")
val eve = client.register("eve")
val chat = client.createChat(alice, "access", listOf(alice.id))
val key = UUID.randomUUID().toString()
client.send(alice, chat, "hello", key)
assertEquals(HttpStatusCode.NotFound, client.send(eve, chat, "hello", key).status)
}
@Test
fun `concurrent retries create exactly one message`() = runApp { client ->
val alice = client.register("alice")
val chat = client.createChat(alice, "concurrent", listOf(alice.id))
val key = UUID.randomUUID().toString()
val responses = withContext(Dispatchers.Default) {
coroutineScope {
(0 until 20).map { async { client.send(alice, chat, "once", key) } }.awaitAll()
}
}
assertEquals(List(20) { HttpStatusCode.Created }, responses.map { it.status })
assertEquals(1, responses.map { it.body<Message>() }.toSet().size)
assertEquals(1, client.history(alice, chat).size)
}
@Test
fun `expired key can be used for a new message`() = runApp(idempotencyTtlSeconds = 1) { client ->
val alice = client.register("alice")
val chat = client.createChat(alice, "ttl", listOf(alice.id))
val key = UUID.randomUUID().toString()
val first = client.send(alice, chat, "hello", key).body<Message>()
delay(1500)
val second = client.send(alice, chat, "hello again", key)
assertEquals(HttpStatusCode.Created, second.status)
assertNotEquals(first.id, second.body<Message>().id)
}
}
@@ -0,0 +1,26 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.support.runApp
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.http.HttpStatusCode
import kotlin.test.Test
import kotlin.test.assertEquals
class CorsTest {
@Test
fun `page of the API itself may call it`() = runApp { client ->
val response = client.get("/health/ready") { header("Origin", "http://localhost") }
assertEquals(HttpStatusCode.OK, response.status)
}
@Test
fun `unknown origin is rejected`() = runApp { client ->
val response = client.get("/health/ready") { header("Origin", "http://evil.example") }
assertEquals(HttpStatusCode.Forbidden, response.status)
}
}
@@ -8,6 +8,7 @@ import com.mtusi.messenger.main.support.TestRedis
import com.mtusi.messenger.main.support.TestUser
import com.mtusi.messenger.main.support.auth
import com.mtusi.messenger.main.support.createChat
import com.mtusi.messenger.main.support.idempotencyKey
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import com.mtusi.messenger.main.utils.computeSha256
@@ -176,6 +177,7 @@ class DependencyFailureTest {
HttpStatusCode.Unauthorized,
client.post("/api/v1/chats/${chat.id}/messages") {
auth(alice)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest(text = "after logout"))
}.status
@@ -0,0 +1,30 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import kotlin.test.Test
import kotlin.test.assertEquals
class InstanceIdTest {
@Test
fun `every response names the replica`() = runApp { client ->
val alice = client.register("alice")
val responses = listOf(
client.get("/health/live"),
client.get("/health/ready"),
client.get("/api/v1/users/me") { header("Authorization", "Bearer ${alice.token}") },
client.get("/api/v1/users/me"),
client.get("/api/v1/chats/not-a-uuid") { header("Authorization", "Bearer ${alice.token}") },
client.post("/api/v1/chats") { header("Authorization", "Bearer ${alice.token}") },
client.get("/no/such/route")
)
assertEquals(List(responses.size) { "test-instance" }, responses.map { it.headers["X-Instance-Id"] })
}
}
@@ -13,6 +13,7 @@ import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.basicAuth
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
@@ -56,6 +57,7 @@ private fun testConfig(
database: PostgreSQLContainer<*>,
databaseConnectionTimeoutMs: Long,
redis: RedisEndpoint,
idempotencyTtlSeconds: Long,
) = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
@@ -75,6 +77,9 @@ private fun testConfig(
"authentication.realm" to "messenger",
"authentication.sessionTtlSeconds" to sessionTtlSeconds,
"authentication.sessionCacheTtlSeconds" to 60,
"messages.idempotencyTtlSeconds" to idempotencyTtlSeconds,
"instance.id" to "test-instance",
"cors.allowSameOrigin" to true,
)
)
)
@@ -87,10 +92,11 @@ fun runApp(
database: PostgreSQLContainer<*> = TestDatabase.container,
databaseConnectionTimeoutMs: Long = 10000,
redis: RedisEndpoint = TestRedis.endpoint(),
idempotencyTtlSeconds: Long = 86400,
block: suspend ApplicationTestBuilder.(HttpClient) -> Unit
) = testApplication {
environment {
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis)
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis, idempotencyTtlSeconds)
}
application {
module()
@@ -137,6 +143,11 @@ suspend fun HttpClient.register(prefix: String): TestUser {
fun HttpRequestBuilder.auth(user: TestUser) = bearerAuth(user.token)
/**
* Every message POST needs its own key since lab3; pass the same key to model a retry.
*/
fun HttpRequestBuilder.idempotencyKey(key: String = UUID.randomUUID().toString()) = header("Idempotency-Key", key)
suspend fun HttpClient.createChat(
creator: TestUser,
title: String,