Completed for a grade of three

This commit is contained in:
2026-11-18 13:55:24 +03:00
parent cd84a6fd36
commit 248f8a5cb0
77 changed files with 4100 additions and 251 deletions
@@ -9,21 +9,35 @@ 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.configureJobBroker
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.configureSessionRevocationSync
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>) {
val command = args.firstOrNull()
// `migrate` applies database migrations and exits; the API replicas start with migrations already in place.
if (args.firstOrNull() == "migrate") {
if (command == "migrate") {
return migrateDatabase()
}
if (command == "worker") {
val workerArgs = arrayOf(
"-config=worker.conf",
*args.drop(1).toTypedArray()
)
return EngineMain.main(workerArgs)
}
EngineMain.main(args)
}
@@ -31,6 +45,7 @@ fun Application.module() {
configureKoin()
configureDatabase()
configureJobBroker()
configureRedis()
configureGracefulShutdown()
configureSessionRevocationSync()
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.config.broker
interface BrokerConfig {
val host: String
val port: Int
val queue: String
val username: String
val password: String?
val passwordFile: String?
val connectionTimeoutMs: Int
val operationTimeoutMs: Int
}
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.config.broker
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 DefaultBrokerConfig(
@Provided app: Application
) : BrokerConfig by (
app.environment.config
.propertyOrNull("broker")
?.getAs<SerialBrokerConfig>()
?: SerialBrokerConfig()
)
@@ -0,0 +1,15 @@
package com.mtusi.messenger.main.config.broker
import kotlinx.serialization.Serializable
@Serializable
data class SerialBrokerConfig(
override val host: String = "localhost",
override val port: Int = 5672,
override val username: String = "messenger",
override val password: String? = null,
override val passwordFile: String? = null,
override val queue: String = "attachment.process.v1",
override val connectionTimeoutMs: Int = 3000,
override val operationTimeoutMs: Int = 8000
) : BrokerConfig
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.config.worker
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 DefaultWorkerConfig(
@Provided app: Application
) : WorkerConfig by (
app.environment.config
.propertyOrNull("worker")
?.getAs<SerialWorkerConfig>()
?: SerialWorkerConfig()
)
@@ -0,0 +1,20 @@
package com.mtusi.messenger.main.config.worker
import kotlinx.serialization.Serializable
@Serializable
data class SerialWorkerConfig(
override val concurrency: Int = 1,
override val maxAttempts: Int = 5,
override val timeoutSeconds: Long = 60,
override val stagingRetentionSeconds: Long = 86400
) : WorkerConfig {
init {
require(concurrency in 1..4)
require(maxAttempts in 1..100)
require(timeoutSeconds in 1..3600)
require(stagingRetentionSeconds >= 3600)
}
}
@@ -0,0 +1,10 @@
package com.mtusi.messenger.main.config.worker
interface WorkerConfig {
val concurrency: Int
val maxAttempts: Int
val timeoutSeconds: Long
val stagingRetentionSeconds: Long
}
@@ -7,19 +7,28 @@ 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 io.ktor.http.BadContentTypeFormatException
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.server.auth.authenticate
import io.ktor.server.request.contentLength
import io.ktor.server.request.contentType
import io.ktor.server.request.receiveChannel
import io.ktor.server.response.header
import io.ktor.server.response.respond
import io.ktor.server.response.respondBytes
import io.ktor.server.routing.Routing
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.utils.io.readAvailable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.koin.ktor.ext.inject
import kotlin.time.Duration.Companion.milliseconds
fun Routing.configureAttachmentRouting() {
@@ -34,20 +43,32 @@ fun Routing.configureAttachmentRouting() {
val actor = call.currentUser
val chatId = requireUuid(call.parameters["chat_id"], "chat_id")
service.requireMember(chatId, actor.id)
service.requireMember(
chatId = chatId,
actorId = 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() }) {
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()
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")
}
@@ -63,44 +84,89 @@ fun Routing.configureAttachmentRouting() {
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
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)
val attachment = service.upload(
chatId = chatId,
actorId = actor.id,
filename = filename,
contentType = type,
file = file
)
call.respond(HttpStatusCode.Accepted, attachment)
}
}
}
get("/api/v1/attachments/{id}") {
call.respond(service.find(requireUuid(call.parameters["id"], "id"), call.currentUser.id))
val id = requireUuid(call.parameters["id"], "id")
val attachment = service.find(
id = id,
actorId = call.currentUser.id
)
call.respond(attachment)
}
get("/api/v1/attachments/{id}/content") {
val attachment = service.find(requireUuid(call.parameters["id"], "id"), call.currentUser.id)
val id = requireUuid(call.parameters["id"], "id")
val attachment = service.find(
id = id,
actorId = call.currentUser.id
)
if ((call.request.queryParameters["variant"] ?: "original") != "original") {
throw ApiException(ErrorCode.NOT_FOUND, "variant not found")
val variant = call.request.queryParameters["variant"] ?: "original"
if (attachment.status != "ready") {
throw ApiException(ErrorCode.CONFLICT, "attachment is not ready")
}
val contentType = if (variant == "original") {
attachment.contentType
} else {
attachment.variants
.firstOrNull { it.name == variant }
?.contentType
?: 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))
val bytes = service.content(
attachment = attachment,
variant = variant
)
call.respondBytes(
bytes = bytes,
contentType = ContentType.parse(contentType)
)
}
}
}
@@ -2,13 +2,11 @@ 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.services.attachment.jobs.JobBrokerService
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.ObjectStorageService
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
@@ -16,8 +14,11 @@ 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.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import org.koin.ktor.ext.inject
fun Routing.configureHealthRouting() = route("/health") {
@@ -25,9 +26,10 @@ fun Routing.configureHealthRouting() = route("/health") {
call.respond(HttpStatusCode.OK, HealthResponse())
}
val storage by inject<ObjectStorageRepository>()
val storage by inject<ObjectStorageService>()
val broker by inject<JobBrokerService>()
// PostgreSQL and S3 are dependencies of the synchronous path; Redis has a DB fallback.
// Readiness checks PostgreSQL, S3 and RabbitMQ. Redis has a DB fallback.
get("ready") {
// SIGTERM received: leave the balancer's rotation while requests in flight are still being finished.
@@ -40,6 +42,7 @@ fun Routing.configureHealthRouting() = route("/health") {
suspendedTransaction {
exec("SELECT 1")
}
true
} catch (cause: Exception) {
@@ -48,6 +51,7 @@ fun Routing.configureHealthRouting() = route("/health") {
}
call.application.log.warn("Readiness check failed: ${cause.message}")
false
}
@@ -56,11 +60,20 @@ fun Routing.configureHealthRouting() = route("/health") {
return@get
}
if (!withContext(Dispatchers.IO) { storage.ready() }) {
val isStorageReachable = withContext(Dispatchers.IO) {
storage.ready()
}
if (!isStorageReachable) {
call.respondError(ErrorCode.UNAVAILABLE, "object storage unavailable")
return@get
}
if (!broker.ready()) {
call.respondError(ErrorCode.UNAVAILABLE, "job broker unavailable")
return@get
}
call.respond(HttpStatusCode.OK, HealthResponse())
}
@@ -16,6 +16,6 @@ data class Attachment(
val createdAt: Instant,
val updatedAt: Instant = createdAt,
val status: String = "ready",
val variants: List<String> = emptyList(),
val variants: List<AttachmentVariant> = emptyList(),
val errorCode: String? = null,
)
@@ -0,0 +1,25 @@
package com.mtusi.messenger.main.infrastructure.dto
import com.mtusi.messenger.main.compat.serializers.SerialUUID
import kotlinx.serialization.Required
import kotlinx.serialization.Serializable
import kotlin.time.Instant
@Serializable
data class AttachmentJob(
val jobId: SerialUUID,
val attachmentId: SerialUUID,
val createdAt: Instant,
@Required
val schemaVersion: Int = 1,
@Required
val type: String = "attachment.process.v1",
@Required
val pipelineVersion: Int = 1,
@Required
val attempt: Int = 1,
)
@@ -0,0 +1,13 @@
package com.mtusi.messenger.main.infrastructure.dto
import kotlinx.serialization.Serializable
@Serializable
data class AttachmentVariant(
val name: String,
val contentType: String,
val sizeBytes: Long,
val width: Int,
val height: Int,
val sha256: String,
)
@@ -0,0 +1,39 @@
package com.mtusi.messenger.main.infrastructure.dto
data class ProcessedImage(
val bytes: ByteArray,
val width: Int,
val height: Int,
val contentType: String = "image/jpeg"
) {
override fun equals(
other: Any?
): Boolean {
if (this === other) {
return true
}
if (javaClass != other?.javaClass) {
return false
}
other as ProcessedImage
return width == other.width &&
height == other.height &&
bytes.contentEquals(other.bytes) &&
contentType == other.contentType
}
override fun hashCode(): Int {
var result = width
result = 31 * result + height
result = 31 * result + bytes.contentHashCode()
result = 31 * result + contentType.hashCode()
return result
}
}
@@ -0,0 +1,24 @@
package com.mtusi.messenger.main.infrastructure.models.attachment
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.core.java.javaUUID
import org.jetbrains.exposed.v1.datetime.timestamp
object AttachmentJobModel : UUIDTable("attachment_jobs") {
val attachmentId = reference(
name = "attachment_id",
foreign = AttachmentModel
).uniqueIndex()
val pipelineVersion = integer("pipeline_version").default(1)
val attempts = integer("attempts").default(0)
val leaseToken = javaUUID("lease_token").nullable()
val leaseUntil = timestamp("lease_until").nullable()
val lastErrorCode = varchar("last_error_code", 64).nullable()
val nextAttemptAt = timestamp("next_attempt_at").nullable()
val createdAt = timestamp("created_at")
val legacyOriginal = bool("legacy_original").default(false)
val legacyDispatchPending = bool("legacy_dispatch_pending").default(false)
}
@@ -13,4 +13,8 @@ object AttachmentModel : UUIDTable("attachments") {
val sizeBytes = long("size_bytes")
val sha256 = varchar("sha256", 64)
val createdAt = timestamp("created_at")
val updatedAt = timestamp("updated_at")
val status = varchar("status", 16).default("ready")
val stagingCleaned = bool("staging_cleaned").default(false)
val errorCode = varchar("error_code", 64).nullable()
}
@@ -0,0 +1,23 @@
package com.mtusi.messenger.main.infrastructure.models.attachment
import org.jetbrains.exposed.v1.core.ReferenceOption
import org.jetbrains.exposed.v1.core.Table
object AttachmentVariantModel : Table("attachment_variants") {
val attachmentId = reference(
name = "attachment_id",
foreign = AttachmentModel,
onDelete = ReferenceOption.CASCADE
)
val name = varchar("name", 16)
val contentType = varchar("content_type", 32)
val sizeBytes = long("size_bytes")
val width = integer("width")
val height = integer("height")
val sha256 = varchar("sha256", 64)
override val primaryKey = PrimaryKey(attachmentId, name)
}
@@ -1,7 +1,9 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import com.mtusi.messenger.main.infrastructure.dto.AttachmentVariant
import java.util.UUID
import kotlin.time.Instant
interface AttachmentRepository {
@@ -9,6 +11,35 @@ interface AttachmentRepository {
fun findById(id: UUID): Attachment?
fun findStatusesInChat(
chatId: UUID,
ids: List<UUID>,
lockForUpdate: Boolean = false
): List<String>
fun setState(
id: UUID,
status: String,
errorCode: String? = null
)
fun markEnqueueFailed(
id: UUID
)
fun markStagingCleaned(
id: UUID
)
fun findExpiredStorage(
before: Instant
): List<ExpiredAttachmentStorage>
fun publish(
id: UUID,
variant: AttachmentVariant
)
fun attach(
messageId: UUID,
ids: List<UUID>
@@ -18,3 +49,9 @@ interface AttachmentRepository {
fun idsForMessages(messageIds: List<UUID>): Map<UUID, List<UUID>>
}
data class ExpiredAttachmentStorage(
val id: UUID,
val failed: Boolean,
val legacyOriginal: Boolean
)
@@ -1,21 +1,34 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import com.mtusi.messenger.main.infrastructure.dto.AttachmentVariant
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentJobModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentVariantModel
import com.mtusi.messenger.main.infrastructure.models.attachment.MessageAttachmentModel
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import com.mtusi.messenger.main.utils.nowMicros
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.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.inList
import org.jetbrains.exposed.v1.core.less
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.insertIgnore
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
import kotlin.time.Clock
import kotlin.time.Instant
@Single
class ExposedAttachmentRepository : AttachmentRepository {
override fun create(attachment: Attachment) {
override fun create(
attachment: Attachment
) {
AttachmentModel.insert {
it[id] = attachment.id
it[chatId] = attachment.chatId
@@ -25,17 +38,129 @@ class ExposedAttachmentRepository : AttachmentRepository {
it[sizeBytes] = attachment.sizeBytes
it[sha256] = attachment.sha256
it[createdAt] = attachment.createdAt
it[updatedAt] = attachment.updatedAt
it[status] = attachment.status
it[errorCode] = attachment.errorCode
}
}
override fun findById(
id: UUID
): Attachment? {
return AttachmentModel
val rows = AttachmentModel
.leftJoin(AttachmentVariantModel)
.selectAll()
.where(AttachmentModel.id eq id)
.firstOrNull()
?.toAttachment()
.orderBy(AttachmentVariantModel.name to SortOrder.ASC)
.toList()
val attachment = rows.firstOrNull()
?: return null
val variants = rows.mapNotNull { it.toAttachmentVariantOrNull() }
return attachment.toAttachment(variants)
}
override fun findStatusesInChat(
chatId: UUID,
ids: List<UUID>,
lockForUpdate: Boolean
): List<String> {
if (ids.isEmpty()) {
return emptyList()
}
val query = AttachmentModel
.select(AttachmentModel.status)
.where((AttachmentModel.chatId eq chatId) and (AttachmentModel.id inList ids))
if (lockForUpdate) {
// Requests with overlapping attachments take locks in the same order.
query
.orderBy(AttachmentModel.id to SortOrder.ASC)
.forUpdate()
}
return query.map { it[AttachmentModel.status] }
}
override fun setState(
id: UUID,
status: String,
errorCode: String?
) {
AttachmentModel.update(where = { AttachmentModel.id eq id }) {
it[this.status] = status
it[this.errorCode] = errorCode
it[updatedAt] = Clock.System.nowMicros()
}
}
override fun markEnqueueFailed(
id: UUID
) {
AttachmentModel.update(
where = {
(AttachmentModel.id eq id) and (AttachmentModel.status eq "queued")
}
) {
it[status] = "failed"
it[errorCode] = "enqueue_failed"
it[updatedAt] = Clock.System.nowMicros()
}
}
override fun markStagingCleaned(
id: UUID
) {
AttachmentModel.update(where = { AttachmentModel.id eq id }) {
it[stagingCleaned] = true
}
}
override fun findExpiredStorage(
before: Instant
): List<ExpiredAttachmentStorage> {
return AttachmentModel
.leftJoin(AttachmentJobModel)
.select(AttachmentModel.id, AttachmentModel.status, AttachmentJobModel.legacyOriginal)
.where(
(AttachmentModel.status inList listOf("ready", "failed"))
.and(AttachmentModel.updatedAt less before)
.and(AttachmentModel.stagingCleaned eq false)
)
.orderBy(AttachmentModel.updatedAt to SortOrder.ASC)
.limit(100)
.map {
ExpiredAttachmentStorage(
id = it[AttachmentModel.id].value,
failed = it[AttachmentModel.status] == "failed",
legacyOriginal = it.getOrNull(AttachmentJobModel.legacyOriginal) == true
)
}
}
override fun publish(
id: UUID,
variant: AttachmentVariant
) {
AttachmentVariantModel.insertIgnore {
it[attachmentId] = id
it[name] = variant.name
it[contentType] = variant.contentType
it[sizeBytes] = variant.sizeBytes
it[width] = variant.width
it[height] = variant.height
it[sha256] = variant.sha256
}
setState(
id = id,
status = "ready"
)
}
override fun attach(
@@ -74,7 +199,9 @@ class ExposedAttachmentRepository : AttachmentRepository {
)
}
private fun ResultRow.toAttachment() = Attachment(
private fun ResultRow.toAttachment(
variants: List<AttachmentVariant>
) = Attachment(
id = this[AttachmentModel.id].value,
chatId = this[AttachmentModel.chatId].value,
ownerId = this[AttachmentModel.ownerId].value,
@@ -82,7 +209,26 @@ class ExposedAttachmentRepository : AttachmentRepository {
contentType = this[AttachmentModel.contentType],
sizeBytes = this[AttachmentModel.sizeBytes],
sha256 = this[AttachmentModel.sha256],
createdAt = this[AttachmentModel.createdAt]
createdAt = this[AttachmentModel.createdAt],
updatedAt = this[AttachmentModel.updatedAt],
status = this[AttachmentModel.status],
errorCode = this[AttachmentModel.errorCode],
variants = variants
)
private fun ResultRow.toAttachmentVariantOrNull(): AttachmentVariant? {
val name = getOrNull(AttachmentVariantModel.name)
?: return null
return AttachmentVariant(
name = name,
contentType = this[AttachmentVariantModel.contentType],
sizeBytes = this[AttachmentVariantModel.sizeBytes],
width = this[AttachmentVariantModel.width],
height = this[AttachmentVariantModel.height],
sha256 = this[AttachmentVariantModel.sha256]
)
}
}
@@ -0,0 +1,59 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import com.mtusi.messenger.main.infrastructure.dto.AttachmentVariant
import java.util.UUID
interface AttachmentJobRepository {
fun create(
job: AttachmentJob
)
fun claim(
job: AttachmentJob,
token: UUID,
maxAttempts: Int,
leaseSeconds: Long
): JobClaim
fun complete(
job: AttachmentJob,
token: UUID,
variant: AttachmentVariant
): Boolean
fun fail(
job: AttachmentJob,
token: UUID,
errorCode: String,
permanent: Boolean,
maxAttempts: Int
): Boolean
fun findPendingLegacyJobs(
limit: Int
): List<AttachmentJob>
fun markLegacyJobDispatched(
id: UUID
)
}
sealed interface JobClaim {
data object Complete : JobClaim
data object Busy : JobClaim
data class Retry(
val attempt: Int
) : JobClaim
data class Acquired(
val attempt: Int,
val legacyOriginal: Boolean = false
) : JobClaim
}
@@ -0,0 +1,250 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import com.mtusi.messenger.main.infrastructure.dto.AttachmentVariant
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentJobModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.utils.exposed.operations.plus
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.eq
import org.jetbrains.exposed.v1.core.greater
import org.jetbrains.exposed.v1.core.isNotNull
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
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 ExposedAttachmentJobRepository(
private val attachmentRepository: AttachmentRepository
) : AttachmentJobRepository {
override fun create(
job: AttachmentJob
) {
AttachmentJobModel.insert {
it[id] = job.jobId
it[attachmentId] = job.attachmentId
it[pipelineVersion] = job.pipelineVersion
it[createdAt] = job.createdAt
}
}
override fun claim(
job: AttachmentJob,
token: UUID,
maxAttempts: Int,
leaseSeconds: Long
): JobClaim {
val row = lock(job) ?: return JobClaim.Complete
val status = AttachmentModel
.select(AttachmentModel.status)
.where(AttachmentModel.id eq job.attachmentId)
.forUpdate()
.single()[AttachmentModel.status]
if (status in setOf("ready", "failed")) {
return JobClaim.Complete
}
val activeLease = AttachmentJobModel.leaseUntil.isNotNull()
.and(AttachmentJobModel.leaseUntil greater CurrentTimestamp)
val busy = AttachmentJobModel
.select(activeLease)
.where(AttachmentJobModel.id eq job.jobId)
.single()
.get(activeLease) == true
if (busy) {
return JobClaim.Busy
}
val attempts = row[AttachmentJobModel.attempts]
if (attempts >= maxAttempts) {
attachmentRepository.setState(
id = job.attachmentId,
status = "failed",
errorCode = "retry_exhausted"
)
clearLease(job.jobId)
return JobClaim.Complete
}
val nextAttempt = attempts + 1
if (job.attempt != nextAttempt) {
if (row[AttachmentJobModel.leaseToken] != null) {
queueRetry(
id = job.jobId,
attachmentId = job.attachmentId,
errorCode = "lease_expired"
)
}
return JobClaim.Retry(attempt = nextAttempt)
}
AttachmentJobModel.update(where = { AttachmentJobModel.id eq job.jobId }) {
it[this.attempts] = nextAttempt
it[leaseToken] = token
it[leaseUntil] = CurrentTimestamp + longLiteral(leaseSeconds)
it[nextAttemptAt] = null
}
attachmentRepository.setState(
id = job.attachmentId,
status = "processing"
)
return JobClaim.Acquired(
attempt = nextAttempt,
legacyOriginal = row[AttachmentJobModel.legacyOriginal]
)
}
override fun complete(
job: AttachmentJob,
token: UUID,
variant: AttachmentVariant
): Boolean {
val row = lock(job) ?: return false
if (row[AttachmentJobModel.leaseToken] != token) {
return false
}
attachmentRepository.publish(
id = job.attachmentId,
variant = variant
)
clearLease(job.jobId)
return true
}
override fun fail(
job: AttachmentJob,
token: UUID,
errorCode: String,
permanent: Boolean,
maxAttempts: Int
): Boolean {
val row = lock(job) ?: return true
if (row[AttachmentJobModel.leaseToken] != token) {
return false
}
val terminal = permanent || row[AttachmentJobModel.attempts] >= maxAttempts
if (!terminal) {
queueRetry(
id = job.jobId,
attachmentId = job.attachmentId,
errorCode = errorCode
)
return false
}
attachmentRepository.setState(
id = job.attachmentId,
status = "failed",
errorCode = if (permanent) errorCode else "retry_exhausted"
)
AttachmentJobModel.update(where = { AttachmentJobModel.id eq job.jobId }) {
it[leaseToken] = null
it[leaseUntil] = null
it[lastErrorCode] = errorCode
it[nextAttemptAt] = null
}
return true
}
private fun queueRetry(
id: UUID,
attachmentId: UUID,
errorCode: String
) {
attachmentRepository.setState(
id = attachmentId,
status = "queued"
)
AttachmentJobModel.update(where = { AttachmentJobModel.id eq id }) {
it[leaseToken] = null
it[leaseUntil] = null
it[lastErrorCode] = errorCode
it[nextAttemptAt] = CurrentTimestamp
}
}
override fun findPendingLegacyJobs(
limit: Int
): List<AttachmentJob> {
return AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.legacyDispatchPending eq true)
.orderBy(AttachmentJobModel.createdAt to SortOrder.ASC, AttachmentJobModel.id to SortOrder.ASC)
.limit(limit)
.map {
AttachmentJob(
jobId = it[AttachmentJobModel.id].value,
attachmentId = it[AttachmentJobModel.attachmentId].value,
pipelineVersion = it[AttachmentJobModel.pipelineVersion],
createdAt = it[AttachmentJobModel.createdAt]
)
}
}
override fun markLegacyJobDispatched(
id: UUID
) {
AttachmentJobModel.update(where = { AttachmentJobModel.id eq id }) {
it[legacyDispatchPending] = false
}
}
private fun lock(
job: AttachmentJob
): ResultRow? {
return AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.id eq job.jobId)
.forUpdate()
.firstOrNull()
?.takeIf {
it[AttachmentJobModel.attachmentId].value == job.attachmentId &&
it[AttachmentJobModel.pipelineVersion] == job.pipelineVersion
}
}
private fun clearLease(
id: UUID
) {
AttachmentJobModel.update(where = { AttachmentJobModel.id eq id }) {
it[leaseToken] = null
it[leaseUntil] = null
it[nextAttemptAt] = null
}
}
}
@@ -1,19 +0,0 @@
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
}
@@ -1,16 +1,23 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.config.worker.WorkerConfig
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.UploadJournalRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.ObjectStorageService
import com.mtusi.messenger.main.plugins.suspendedTransaction
import kotlinx.coroutines.CancellationException
import org.koin.core.annotation.Single
import kotlin.time.Clock
import kotlin.time.Duration.Companion.seconds
@Single
class AttachmentCleanupService(
private val journalRepository: UploadJournalRepository,
private val objectStorageRepository: ObjectStorageRepository
private val objectStorageService: ObjectStorageService,
private val attachmentRepository: AttachmentRepository,
private val config: WorkerConfig
) {
suspend fun cleanup(): Int {
val ids = suspendedTransaction {
@@ -18,9 +25,10 @@ class AttachmentCleanupService(
}
var deleted = 0
ids.forEach { id ->
try {
objectStorageRepository.delete(id)
objectStorageService.delete(id)
deleted++
} catch (cause: CancellationException) {
throw cause
@@ -29,6 +37,34 @@ class AttachmentCleanupService(
}
}
val expired = suspendedTransaction {
attachmentRepository.findExpiredStorage(
before = Clock.System.now() - config.stagingRetentionSeconds.seconds
)
}
expired.forEach { attachment ->
try {
when {
attachment.failed && !attachment.legacyOriginal ->
objectStorageService.delete(attachment.id)
attachment.failed ->
objectStorageService.deleteThumbnail(attachment.id)
!attachment.legacyOriginal ->
objectStorageService.deleteStaging(attachment.id)
}
suspendedTransaction {
attachmentRepository.markStagingCleaned(attachment.id)
}
} catch (cause: CancellationException) {
throw cause
} catch (_: Exception) {
// Terminal metadata remains available for a later cleanup retry.
}
}
return deleted
}
}
@@ -24,5 +24,9 @@ interface AttachmentService {
actorId: UUID
): Attachment
suspend fun content(attachment: Attachment): ByteArray
suspend fun content(
attachment: Attachment,
variant: String = "original"
): ByteArray
}
@@ -0,0 +1,171 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.config.worker.WorkerConfig
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import com.mtusi.messenger.main.infrastructure.dto.AttachmentVariant
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.AttachmentJobRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.JobClaim
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.JobBrokerService
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.ObjectStorageService
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 kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
@Single
class DefaultAttachmentProcessingService(
private val jobRepository: AttachmentJobRepository,
private val attachmentRepository: AttachmentRepository,
private val objectStorageService: ObjectStorageService,
private val imageProcessingService: ImageProcessingService,
private val jobBrokerService: JobBrokerService,
private val config: WorkerConfig
) {
suspend fun process(
job: AttachmentJob
): Boolean {
val token = UUID.randomUUID()
val claim = suspendedTransaction {
jobRepository.claim(
job = job,
token = token,
maxAttempts = config.maxAttempts,
leaseSeconds = config.timeoutSeconds + 15
)
}
when (claim) {
JobClaim.Complete -> return true
JobClaim.Busy -> {
// Pace redeliveries while the lease is active. Publish to the tail and
// confirm before acknowledging the original delivery.
delay(250.milliseconds)
jobBrokerService.publish(job)
return true
}
is JobClaim.Retry -> {
jobBrokerService.publish(job.copy(attempt = claim.attempt))
return true
}
is JobClaim.Acquired -> Unit
}
try {
val completed = withTimeoutOrNull(config.timeoutSeconds.seconds) {
processAttachment(
job = job,
token = token,
legacyOriginal = claim.legacyOriginal
)
} ?: throw ProcessingTimeoutException()
return completed
} catch (cause: CancellationException) {
// Leave the delivery unacknowledged; a new worker can reclaim the expired lease.
throw cause
} catch (cause: Exception) {
val isPermanent = cause is ApiException && cause.code in setOf(
ErrorCode.UNSUPPORTED_MEDIA_TYPE,
ErrorCode.PAYLOAD_TOO_LARGE
)
val errorCode = when {
isPermanent -> "invalid_image"
cause is ProcessingTimeoutException -> "processing_timeout"
cause is ApiException && cause.code == ErrorCode.UNAVAILABLE -> "storage_unavailable"
else -> "processing_failed"
}
val isTerminal = suspendedTransaction {
jobRepository.fail(
job = job,
token = token,
errorCode = errorCode,
permanent = isPermanent,
maxAttempts = config.maxAttempts
)
}
if (!isTerminal) {
jobBrokerService.publish(job.copy(attempt = claim.attempt + 1))
}
return true
}
}
private class ProcessingTimeoutException : RuntimeException()
private suspend fun processAttachment(
job: AttachmentJob,
token: UUID,
legacyOriginal: Boolean
): Boolean {
val attachment = suspendedTransaction {
checkNotNull(attachmentRepository.findById(job.attachmentId))
}
val bytes = if (legacyOriginal) {
objectStorageService.get(attachment.id)
} else {
objectStorageService.getStaging(attachment.id)
}
if (bytes.size.toLong() != attachment.sizeBytes || bytes.computeSha256() != attachment.sha256) {
throw ApiException(
code = ErrorCode.UNSUPPORTED_MEDIA_TYPE,
message = "invalid source image"
)
}
val thumbnail = imageProcessingService.thumbnail(
bytes = bytes,
declaredType = attachment.contentType
)
if (!legacyOriginal) {
objectStorageService.put(
id = attachment.id,
bytes = bytes,
contentType = attachment.contentType
)
}
objectStorageService.putThumbnail(
id = attachment.id,
bytes = thumbnail.bytes
)
return suspendedTransaction {
jobRepository.complete(
job = job,
token = token,
variant = AttachmentVariant(
name = "thumbnail",
contentType = thumbnail.contentType,
sizeBytes = thumbnail.bytes.size.toLong(),
width = thumbnail.width,
height = thumbnail.height,
sha256 = thumbnail.bytes.computeSha256()
)
)
}
}
}
@@ -1,16 +1,21 @@
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.dto.AttachmentJob
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.attachment.UploadJournalRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.AttachmentJobRepository
import com.mtusi.messenger.main.infrastructure.repositories.chat.ChatRepository
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.JobBrokerService
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.ObjectStorageService
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.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import org.koin.core.annotation.Single
import java.io.File
@@ -22,14 +27,24 @@ class DefaultAttachmentService(
private val journalRepository: UploadJournalRepository,
private val attachmentRepository: AttachmentRepository,
private val chatRepository: ChatRepository,
private val objectStorageRepository: ObjectStorageRepository,
private val objectStorageService: ObjectStorageService,
private val jobRepository: AttachmentJobRepository,
private val jobBrokerService: JobBrokerService
) : AttachmentService {
override suspend fun requireMember(
chatId: UUID,
actorId: UUID
) {
if (!suspendedTransaction { chatRepository.isMember(chatId, actorId) }) {
val isMember = suspendedTransaction {
chatRepository.isMember(
chatId = chatId,
userId = actorId
)
}
if (!isMember) {
notFound()
}
}
@@ -42,11 +57,16 @@ class DefaultAttachmentService(
file: File
): Attachment {
requireMember(chatId, actorId)
requireMember(
chatId = chatId,
actorId = actorId
)
val (type, hash) = withContext(Dispatchers.IO) {
val (validatedType, sha256) = withContext(Dispatchers.IO) {
val bytes = file.readBytes()
ImageValidator.validate(bytes, contentType) to bytes.computeSha256()
val type = ImageValidator.validate(bytes, contentType)
type to bytes.computeSha256()
}
val attachment = Attachment(
@@ -54,24 +74,62 @@ class DefaultAttachmentService(
chatId = chatId,
ownerId = actorId,
filename = filename,
contentType = type,
contentType = validatedType,
sizeBytes = file.length(),
sha256 = hash,
createdAt = Clock.System.nowMicros()
sha256 = sha256,
createdAt = Clock.System.nowMicros(),
status = "queued"
)
suspendedTransaction {
journalRepository.register(attachment.id)
}
objectStorageRepository.put(attachment.id, file, type)
suspendedTransaction {
if (!journalRepository.lockForCompletion(attachment.id)) {
throw ApiException(ErrorCode.UNAVAILABLE, "upload expired")
objectStorageService.putStaging(
id = attachment.id,
file = file,
contentType = validatedType
)
val job = AttachmentJob(
jobId = UUID.randomUUID(),
attachmentId = attachment.id,
createdAt = attachment.createdAt
)
try {
suspendedTransaction {
if (!journalRepository.lockForCompletion(attachment.id)) {
throw ApiException(
code = ErrorCode.UNAVAILABLE,
message = "upload expired"
)
}
attachmentRepository.create(attachment)
jobRepository.create(job)
journalRepository.complete(attachment.id)
}
attachmentRepository.create(attachment)
journalRepository.complete(attachment.id)
jobBrokerService.publish(job)
} catch (cause: CancellationException) {
withContext(NonCancellable) {
runCatching {
suspendedTransaction {
attachmentRepository.markEnqueueFailed(attachment.id)
}
}
}
throw cause
} catch (cause: Exception) {
suspendedTransaction {
attachmentRepository.markEnqueueFailed(attachment.id)
}
throw cause
}
return attachment
}
@@ -79,16 +137,49 @@ class DefaultAttachmentService(
id: UUID,
actorId: UUID
): Attachment = suspendedTransaction {
val attachment = attachmentRepository.findById(id) ?: notFound()
if (!chatRepository.isMember(attachment.chatId, actorId)) {
val attachment = attachmentRepository.findById(id)
?: notFound()
val isMember = chatRepository.isMember(
chatId = attachment.chatId,
userId = actorId
)
if (!isMember) {
notFound()
}
attachment
}
override suspend fun content(attachment: Attachment): ByteArray = withContext(Dispatchers.IO) {
objectStorageRepository.get(attachment.id)
override suspend fun content(
attachment: Attachment,
variant: String
): ByteArray = withContext(Dispatchers.IO) {
if (attachment.status != "ready") {
throw ApiException(
code = ErrorCode.CONFLICT,
message = "attachment is not ready"
)
}
when (variant) {
"original" -> objectStorageService.get(attachment.id)
"thumbnail" -> objectStorageService.getThumbnail(attachment.id)
else -> throw ApiException(
code = ErrorCode.NOT_FOUND,
message = "variant not found"
)
}
}
private fun notFound(): Nothing {
throw ApiException(
code = ErrorCode.NOT_FOUND,
message = "attachment or chat not found"
)
}
private fun notFound(): Nothing = throw ApiException(ErrorCode.NOT_FOUND, "attachment or chat not found")
}
@@ -0,0 +1,206 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.drew.imaging.jpeg.JpegMetadataReader
import com.drew.lang.ByteArrayReader
import com.drew.metadata.Metadata
import com.drew.metadata.exif.ExifIFD0Directory
import com.drew.metadata.exif.ExifReader
import com.mtusi.messenger.main.infrastructure.dto.ProcessedImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import org.koin.core.annotation.Single
import java.awt.Color
import java.awt.RenderingHints
import java.awt.geom.AffineTransform
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import javax.imageio.ImageIO
private const val THUMBNAIL_SIZE = 256
@Single
class DefaultImageProcessingService : ImageProcessingService {
override suspend fun thumbnail(
bytes: ByteArray,
declaredType: String
): ProcessedImage = withContext(Dispatchers.IO) {
currentCoroutineContext().ensureActive()
val original = ImageValidator.decode(
bytes = bytes,
declaredType = declaredType
)
try {
currentCoroutineContext().ensureActive()
val orientation = readOrientation(bytes, declaredType)
val swapDimensions = orientation in 5..8
val orientedWidth = if (swapDimensions) original.height else original.width
val orientedHeight = if (swapDimensions) original.width else original.height
val longestSide = maxOf(orientedWidth, orientedHeight)
val width = if (longestSide <= THUMBNAIL_SIZE) {
orientedWidth
} else {
maxOf(1, (orientedWidth.toLong() * THUMBNAIL_SIZE / longestSide).toInt())
}
val height = if (longestSide <= THUMBNAIL_SIZE) {
orientedHeight
} else {
maxOf(1, (orientedHeight.toLong() * THUMBNAIL_SIZE / longestSide).toInt())
}
val thumbnail = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
try {
val transform = AffineTransform.getScaleInstance(
width.toDouble() / orientedWidth,
height.toDouble() / orientedHeight
).apply {
val orientationCorrection = orientationTransform(
orientation = orientation,
width = original.width,
height = original.height
)
concatenate(orientationCorrection)
}
drawThumbnail(
original = original,
thumbnail = thumbnail,
transform = transform
)
currentCoroutineContext().ensureActive()
val encoded = ByteArrayOutputStream().use { output ->
check(ImageIO.write(thumbnail, "jpeg", output)) {
"JPEG encoder is unavailable"
}
output.toByteArray()
}
ProcessedImage(
bytes = encoded,
width = width,
height = height
)
} finally {
thumbnail.flush()
}
} finally {
original.flush()
}
}
private fun drawThumbnail(
original: BufferedImage,
thumbnail: BufferedImage,
transform: AffineTransform
) {
val graphics = thumbnail.createGraphics()
try {
graphics.color = Color.WHITE
graphics.fillRect(0, 0, thumbnail.width, thumbnail.height)
graphics.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR
)
graphics.setRenderingHint(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY
)
graphics.drawImage(original, transform, null)
} finally {
graphics.dispose()
}
}
private fun readOrientation(
bytes: ByteArray,
declaredType: String
): Int {
// Read only EXIF: generic PNG metadata readers can inflate optional text chunks.
val metadata = if (declaredType == "image/jpeg") {
ByteArrayInputStream(bytes).use { input ->
JpegMetadataReader.readMetadata(input, listOf(ExifReader()))
}
} else {
readPngExif(bytes)
}
return metadata
.getFirstDirectoryOfType(ExifIFD0Directory::class.java)
?.getInteger(ExifIFD0Directory.TAG_ORIENTATION)
?.takeIf { it in 1..8 }
?: 1
}
private fun readPngExif(
bytes: ByteArray
): Metadata {
val metadata = Metadata()
var offset = 8
while (offset + 12 <= bytes.size) {
val length = ByteBuffer.wrap(bytes, offset, 4).int
val type = String(bytes, offset + 4, 4, Charsets.US_ASCII)
if (type == "eXIf") {
val dataOffset = offset + 8
val exif = ByteArrayReader(
bytes.copyOfRange(
fromIndex = dataOffset,
toIndex = dataOffset + length
)
)
ExifReader().extract(exif, metadata)
break
}
offset += length + 12
}
return metadata
}
private fun orientationTransform(
orientation: Int,
width: Int,
height: Int
): AffineTransform {
val sourceWidth = width.toDouble()
val sourceHeight = height.toDouble()
return when (orientation) {
2 -> AffineTransform(-1.0, 0.0, 0.0, 1.0, sourceWidth, 0.0)
3 -> AffineTransform(-1.0, 0.0, 0.0, -1.0, sourceWidth, sourceHeight)
4 -> AffineTransform(1.0, 0.0, 0.0, -1.0, 0.0, sourceHeight)
5 -> AffineTransform(0.0, 1.0, 1.0, 0.0, 0.0, 0.0)
6 -> AffineTransform(0.0, 1.0, -1.0, 0.0, sourceHeight, 0.0)
7 -> AffineTransform(0.0, -1.0, -1.0, 0.0, sourceHeight, sourceWidth)
8 -> AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth)
else -> AffineTransform()
}
}
}
@@ -0,0 +1,12 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.infrastructure.dto.ProcessedImage
interface ImageProcessingService {
suspend fun thumbnail(
bytes: ByteArray,
declaredType: String
): ProcessedImage
}
@@ -2,9 +2,10 @@ 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.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.nio.ByteBuffer
import java.util.zip.CRC32
import java.io.ByteArrayInputStream
import javax.imageio.ImageIO
import javax.imageio.stream.MemoryCacheImageInputStream
@@ -18,6 +19,19 @@ object ImageValidator {
declaredType: String
): String {
decode(
bytes = bytes,
declaredType = declaredType
).flush()
return declaredType
}
fun decode(
bytes: ByteArray,
declaredType: String
): BufferedImage {
if (bytes.size > MAX_ATTACHMENT_BYTES) {
throw ApiException(ErrorCode.PAYLOAD_TOO_LARGE, "file exceeds 10 MiB")
}
@@ -72,13 +86,13 @@ object ImageValidator {
reader.addIIOReadWarningListener { _, _ -> warning = true }
val image = reader.read(0) ?: invalid()
image.flush()
if (warning) {
image.flush()
invalid()
}
return type
return image
} finally {
reader.dispose()
}
@@ -0,0 +1,20 @@
package com.mtusi.messenger.main.infrastructure.services.attachment.jobs
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
interface JobBrokerService {
suspend fun publish(
job: AttachmentJob
)
/** A true result acknowledges a durable effect; false requeues the delivery. */
suspend fun consume(
handler: suspend (AttachmentJob) -> Boolean
)
suspend fun ready(): Boolean
fun close()
}
@@ -0,0 +1,28 @@
package com.mtusi.messenger.main.infrastructure.services.attachment.jobs
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.AttachmentJobRepository
import com.mtusi.messenger.main.plugins.suspendedTransaction
import org.koin.core.annotation.Single
@Single
class LegacyAttachmentDispatchService(
private val jobRepository: AttachmentJobRepository,
private val jobBrokerService: JobBrokerService
) {
suspend fun publishPending() {
val jobs = suspendedTransaction {
jobRepository.findPendingLegacyJobs(limit = 32)
}
for (job in jobs) {
jobBrokerService.publish(job)
suspendedTransaction {
jobRepository.markLegacyJobDispatched(job.jobId)
}
}
}
}
@@ -0,0 +1,314 @@
package com.mtusi.messenger.main.infrastructure.services.attachment.jobs
import com.mtusi.messenger.main.config.broker.BrokerConfig
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.utils.resolveSecret
import com.rabbitmq.client.AMQP
import com.rabbitmq.client.Channel
import com.rabbitmq.client.Connection
import com.rabbitmq.client.ConnectionFactory
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.isActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNamingStrategy
import org.koin.core.annotation.Single
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
private const val MAX_JOB_BYTES = 16 * 1024
@Single
class RabbitMqJobBrokerService(
private val config: BrokerConfig
) : JobBrokerService {
private val logger = LoggerFactory.getLogger(RabbitMqJobBrokerService::class.java)
private val closed = AtomicBoolean(false)
private val publisherMutex = Mutex()
private val consumers = ConcurrentHashMap.newKeySet<Connection>()
@Volatile
private var publisher: Connection? = null
@OptIn(ExperimentalSerializationApi::class)
private val json = Json {
encodeDefaults = true
namingStrategy = JsonNamingStrategy.SnakeCase
}
private val factory by lazy {
ConnectionFactory().apply {
host = config.host
port = config.port
username = config.username
password = requireNotNull(
resolveSecret(
value = config.password,
file = config.passwordFile
)
)
connectionTimeout = config.connectionTimeoutMs
handshakeTimeout = config.operationTimeoutMs
channelRpcTimeout = config.operationTimeoutMs
requestedHeartbeat = 10
isAutomaticRecoveryEnabled = true
networkRecoveryInterval = 1000
}
}
override suspend fun publish(
job: AttachmentJob
) {
require(valid(job)) { "Unsupported attachment job" }
try {
publisherMutex.withLock {
withContext(Dispatchers.IO) {
check(!closed.get())
val connection = publisherConnection()
connection.createChannel().use { channel ->
declareQueue(channel)
channel.confirmSelect()
val returned = AtomicBoolean(false)
channel.addReturnListener { _ ->
returned.set(true)
}
val properties = AMQP.BasicProperties.Builder()
.contentType("application/json")
.contentEncoding("utf-8")
.deliveryMode(2)
.messageId(job.jobId.toString())
.build()
val body = json.encodeToString(job).toByteArray(Charsets.UTF_8)
channel.basicPublish(
"",
config.queue,
true,
properties,
body
)
channel.waitForConfirmsOrDie(config.operationTimeoutMs.toLong())
check(!returned.get()) { "Attachment job was not routed" }
currentCoroutineContext().ensureActive()
}
}
}
} catch (cause: CancellationException) {
throw cause
} catch (_: Exception) {
currentCoroutineContext().ensureActive()
throw ApiException(
code = ErrorCode.UNAVAILABLE,
message = "job broker unavailable"
)
}
}
override suspend fun consume(
handler: suspend (AttachmentJob) -> Boolean
) {
withContext(Dispatchers.IO) {
while (currentCoroutineContext().isActive && !closed.get()) {
try {
val connection = connect("messenger-jobs-worker")
consumers.add(connection)
try {
connection.createChannel().use { channel ->
declareQueue(channel)
channel.basicQos(1)
consumeDeliveries(
connection = connection,
channel = channel,
handler = handler
)
}
} finally {
consumers.remove(connection)
runCatching { connection.abort() }
}
} catch (cause: CancellationException) {
throw cause
} catch (cause: Exception) {
currentCoroutineContext().ensureActive()
if (!closed.get()) {
logger.warn(
"Attachment job consumer disconnected ({}); retrying",
cause.javaClass.simpleName
)
delay(1.seconds)
}
}
}
}
}
override suspend fun ready(): Boolean {
return try {
publisherMutex.withLock {
withContext(Dispatchers.IO) {
check(!closed.get())
val connection = publisherConnection()
connection.createChannel().use(::declareQueue)
true
}
}
} catch (cause: CancellationException) {
throw cause
} catch (_: Exception) {
currentCoroutineContext().ensureActive()
false
}
}
override fun close() {
closed.set(true)
runCatching { publisher?.abort() }
consumers.forEach { connection ->
runCatching { connection.abort() }
}
}
private suspend fun consumeDeliveries(
connection: Connection,
channel: Channel,
handler: suspend (AttachmentJob) -> Boolean
) {
// Waiting for the handler before the next basicGet keeps one delivery in flight.
// Channel or connection closure requeues an unacknowledged job.
while (
currentCoroutineContext().isActive &&
!closed.get() &&
connection.isOpen &&
channel.isOpen
) {
val delivery = channel.basicGet(config.queue, false)
if (delivery == null) {
delay(250.milliseconds)
continue
}
val job = decode(delivery.body)
val deliveryTag = delivery.envelope.deliveryTag
if (job == null) {
channel.basicReject(deliveryTag, false)
logger.warn("Rejected unsupported attachment job envelope")
continue
}
if (handler(job)) {
channel.basicAck(deliveryTag, false)
} else {
channel.basicNack(deliveryTag, false, true)
delay(500.milliseconds)
}
}
}
private fun connect(
name: String
): Connection {
check(!closed.get())
return factory.newConnection(name).also { connection ->
if (closed.get()) {
connection.abort()
error("Attachment job broker is closed")
}
}
}
/** Called under publisherMutex so reconnect does not retain an unused recovery loop. */
private fun publisherConnection(): Connection {
publisher?.let { connection ->
if (connection.isOpen) {
return connection
}
runCatching { connection.abort() }
publisher = null
}
val connection = connect("messenger-jobs-publisher")
publisher = connection
if (closed.get()) {
connection.abort()
error("Attachment job broker is closed")
}
return connection
}
private fun declareQueue(
channel: Channel
) {
channel.queueDeclare(
config.queue,
true,
false,
false,
mapOf("x-queue-type" to "classic")
)
}
private fun decode(
bytes: ByteArray
): AttachmentJob? {
if (bytes.size > MAX_JOB_BYTES) {
return null
}
return runCatching {
json.decodeFromString<AttachmentJob>(bytes.toString(Charsets.UTF_8))
}
.getOrNull()
?.takeIf(::valid)
}
private fun valid(
job: AttachmentJob
): Boolean {
return job.schemaVersion == 1 &&
job.type == "attachment.process.v1" &&
job.pipelineVersion == 1 &&
job.attempt >= 1
}
}
@@ -0,0 +1,46 @@
package com.mtusi.messenger.main.infrastructure.services.attachment.storage
import java.io.File
import java.util.UUID
interface ObjectStorageService {
suspend fun put(
id: UUID,
bytes: ByteArray,
contentType: String
)
suspend fun putStaging(
id: UUID,
file: File,
contentType: String
)
suspend fun getStaging(
id: UUID
): ByteArray
suspend fun deleteStaging(
id: UUID
)
suspend fun putThumbnail(
id: UUID,
bytes: ByteArray
)
suspend fun getThumbnail(
id: UUID
): ByteArray
suspend fun deleteThumbnail(
id: UUID
)
suspend fun get(id: UUID): ByteArray
suspend fun delete(id: UUID)
suspend fun ready(): Boolean
}
@@ -1,4 +1,4 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment.storage
package com.mtusi.messenger.main.infrastructure.services.attachment.storage
import aws.sdk.kotlin.runtime.auth.credentials.StaticCredentialsProvider
import aws.sdk.kotlin.services.s3.S3Client
@@ -22,9 +22,9 @@ import java.util.UUID
import kotlin.time.Duration.Companion.milliseconds
@Single
class S3ObjectStorageRepository(
class S3ObjectStorageService(
private val config: StorageConfig
) : ObjectStorageRepository {
) : ObjectStorageService {
private val client by lazy {
S3Client {
@@ -41,13 +41,33 @@ class S3ObjectStorageRepository(
override suspend fun put(
id: UUID,
file: File,
bytes: ByteArray,
contentType: String
) {
request {
client.putObject {
bucket = config.bucket
key = getObjectKey(id)
body = bytes.asByteStream()
this.contentType = contentType
contentLength = bytes.size.toLong()
}
}
}
override suspend fun get(
id: UUID
): ByteArray = getBytes(getObjectKey(id))
override suspend fun putStaging(
id: UUID,
file: File,
contentType: String
) {
request {
client.putObject {
bucket = config.bucket
key = getStagingKey(id)
body = file.asByteStream()
this.contentType = contentType
contentLength = file.length()
@@ -55,13 +75,72 @@ class S3ObjectStorageRepository(
}
}
override suspend fun get(
override suspend fun getStaging(
id: UUID
): ByteArray = getBytes(getStagingKey(id))
override suspend fun deleteStaging(
id: UUID
) {
deleteKey(getStagingKey(id))
}
override suspend fun putThumbnail(
id: UUID,
bytes: ByteArray
) {
request {
client.putObject {
bucket = config.bucket
key = getThumbnailKey(id)
body = bytes.asByteStream()
contentType = "image/jpeg"
contentLength = bytes.size.toLong()
}
}
}
override suspend fun getThumbnail(
id: UUID
): ByteArray = getBytes(getThumbnailKey(id))
override suspend fun deleteThumbnail(
id: UUID
) {
deleteKey(getThumbnailKey(id))
}
override suspend fun delete(
id: UUID
) {
deleteKey(getObjectKey(id))
deleteStaging(id)
deleteThumbnail(id)
}
override suspend fun ready(): Boolean {
return try {
request {
client.headBucket {
bucket = config.bucket
}
}
true
} catch (_: ApiException) {
false
}
}
private suspend fun getBytes(
key: String
): ByteArray = request {
client.getObject(GetObjectRequest {
bucket = config.bucket
key = getObjectKey(id)
}) { response ->
client.getObject(
GetObjectRequest {
bucket = config.bucket
this.key = key
}
) { response ->
val contentLength = requireNotNull(response.contentLength)
@@ -75,31 +154,28 @@ class S3ObjectStorageRepository(
}
}
override suspend fun delete(
id: UUID
private suspend fun deleteKey(
key: String
) {
request {
client.deleteObject {
bucket = config.bucket
key = getObjectKey(id)
this.key = key
}
}
}
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 fun getObjectKey(id: UUID) = "originals/$id"
private fun getStagingKey(
id: UUID
) = "staging/$id"
private fun getThumbnailKey(
id: UUID
) = "variants/$id/v1/thumbnail.jpg"
private suspend fun <T : Any> request(block: suspend () -> T): T {
return try {
@@ -1,14 +1,14 @@
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.attachment.AttachmentRepository
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.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import com.mtusi.messenger.main.utils.PageKey
import com.mtusi.messenger.main.utils.computeSha256
import com.mtusi.messenger.main.utils.decodeCursor
@@ -44,14 +44,20 @@ class DefaultMessageService(
return MessageCreationResult.ChatNotFound
}
attachmentIds.forEach { id ->
if (attachments.findById(id)?.chatId != chatId)
throw ApiException(
ErrorCode.NOT_FOUND, "attachment not found")
requireAttachmentStatuses(
chatId = chatId,
attachmentIds = attachmentIds
)
val attachmentSuffix = if (attachmentIds.isEmpty()) {
""
} else {
"\u0000attachments:" + attachmentIds.joinToString(",")
}
val requestHash = (text + if (attachmentIds.isEmpty()) "" else "\u0000attachments:" + attachmentIds.joinToString(","))
.toByteArray().computeSha256()
val requestHash = (text + attachmentSuffix)
.toByteArray()
.computeSha256()
val now = Clock.System.nowMicros()
@@ -59,6 +65,19 @@ class DefaultMessageService(
if (idempotencyRepository.claim(senderId, chatId, idempotencyKey, requestHash, now)) {
val statuses = requireAttachmentStatuses(
chatId = chatId,
attachmentIds = attachmentIds,
lockForUpdate = true
)
if ("failed" in statuses) {
throw ApiException(
code = ErrorCode.CONFLICT,
message = "attachment processing failed"
)
}
val message = messageRepository.create(
chatId = chatId,
senderId = senderId,
@@ -103,6 +122,28 @@ class DefaultMessageService(
error("Idempotency key could not be claimed")
}
private fun requireAttachmentStatuses(
chatId: UUID,
attachmentIds: List<UUID>,
lockForUpdate: Boolean = false
): List<String> {
val statuses = attachments.findStatusesInChat(
chatId = chatId,
ids = attachmentIds,
lockForUpdate = lockForUpdate
)
if (statuses.size != attachmentIds.size) {
throw ApiException(
code = ErrorCode.NOT_FOUND,
message = "attachment not found"
)
}
return statuses
}
override fun findPageByChatId(
chatId: UUID,
actorId: UUID,
@@ -2,6 +2,7 @@ package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.infrastructure.services.attachment.AttachmentCleanupService
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationStopping
import io.ktor.server.application.log
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
@@ -14,9 +15,10 @@ fun Application.configureAttachmentCleanup() {
val cleanupService by inject<AttachmentCleanupService>()
launch {
val cleanup = launch {
while (isActive) {
delay(30.seconds)
try {
cleanupService.cleanup()
} catch (cause: CancellationException) {
@@ -26,4 +28,9 @@ fun Application.configureAttachmentCleanup() {
}
}
}
monitor.subscribe(ApplicationStopping) {
cleanup.cancel()
}
}
@@ -0,0 +1,50 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.config.worker.WorkerConfig
import com.mtusi.messenger.main.infrastructure.services.attachment.DefaultAttachmentProcessingService
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.JobBrokerService
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.LegacyAttachmentDispatchService
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationStopping
import io.ktor.server.application.log
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.koin.ktor.ext.get
import kotlin.time.Duration.Companion.seconds
fun Application.configureAttachmentWorker() {
val broker = get<JobBrokerService>()
val processingService = get<DefaultAttachmentProcessingService>()
val legacyDispatchService = get<LegacyAttachmentDispatchService>()
val config = get<WorkerConfig>()
val workers = List(config.concurrency) {
launch {
broker.consume(processingService::process)
}
}
val legacyDispatch = launch {
while (isActive) {
try {
legacyDispatchService.publishPending()
} catch (cause: CancellationException) {
throw cause
} catch (cause: Exception) {
log.warn("Legacy attachment dispatch failed ({}); retrying", cause.javaClass.simpleName)
}
delay(1.seconds)
}
}
monitor.subscribe(ApplicationStopping) {
workers.forEach { it.cancel() }
legacyDispatch.cancel()
broker.close()
}
}
@@ -1,10 +1,12 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.infrastructure.models.attachment.MessageAttachmentModel
import com.mtusi.messenger.main.infrastructure.models.attachment.UploadJournalModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel
import com.mtusi.messenger.main.config.database.DatabaseConfig
import com.mtusi.messenger.main.config.database.SerialDatabaseConfig
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentJobModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentVariantModel
import com.mtusi.messenger.main.infrastructure.models.attachment.MessageAttachmentModel
import com.mtusi.messenger.main.infrastructure.models.attachment.UploadJournalModel
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionModel
import com.mtusi.messenger.main.infrastructure.models.authentication.SessionRevocationModel
import com.mtusi.messenger.main.infrastructure.models.chat.ChatMemberModel
@@ -21,18 +23,19 @@ import io.ktor.server.application.ApplicationStopped
import io.ktor.server.config.HoconApplicationConfig
import io.ktor.server.config.getAs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.flywaydb.core.Flyway
import org.jetbrains.exposed.v1.core.ExperimentalDatabaseMigrationApi
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.core.DatabaseConfig as ExposedDatabaseConfig
import org.jetbrains.exposed.v1.jdbc.Database
import org.jetbrains.exposed.v1.jdbc.JdbcTransaction
import org.jetbrains.exposed.v1.jdbc.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.v1.jdbc.transactions.suspendTransaction
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
import org.jetbrains.exposed.v1.migration.jdbc.MigrationUtils
import org.koin.ktor.ext.inject
import java.io.File
import javax.sql.DataSource
import org.jetbrains.exposed.v1.core.DatabaseConfig as ExposedDatabaseConfig
private const val MIGRATIONS_DIRECTORY = "src/main/resources/migrations"
private const val DEVELOPMENT_DATABASE_CONFIG = "run/development/config/database.conf"
@@ -121,6 +124,8 @@ private fun generateMigration(description: String) {
val tables: Array<Table> = arrayOf(
AttachmentModel,
AttachmentVariantModel,
AttachmentJobModel,
UploadJournalModel,
MessageAttachmentModel,
UserModel,
@@ -175,7 +180,10 @@ private fun generateMigration(description: String) {
}
suspend fun <R> suspendedTransaction(statement: JdbcTransaction.() -> R) = newSuspendedTransaction(
context = Dispatchers.IO,
statement = statement
)
suspend fun <R> suspendedTransaction(
statement: JdbcTransaction.() -> R
): R = withContext(Dispatchers.IO) {
suspendTransaction {
statement()
}
}
@@ -0,0 +1,16 @@
package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.JobBrokerService
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationStopping
import org.koin.ktor.ext.get
fun Application.configureJobBroker() {
val broker = get<JobBrokerService>()
monitor.subscribe(ApplicationStopping) {
broker.close()
}
}
@@ -2,6 +2,7 @@ package com.mtusi.messenger.main.plugins
import com.mtusi.messenger.main.infrastructure.services.authentication.AuthenticationService
import io.ktor.server.application.Application
import io.ktor.server.application.ApplicationStopping
import io.ktor.server.application.log
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
@@ -21,9 +22,10 @@ fun Application.configureSessionRevocationSync() {
val authenticationService by inject<AuthenticationService>()
launch {
val synchronization = launch {
while (isActive) {
delay(SYNC_INTERVAL)
try {
authenticationService.syncPendingRevocations()
} catch (e: CancellationException) {
@@ -33,4 +35,9 @@ fun Application.configureSessionRevocationSync() {
}
}
}
monitor.subscribe(ApplicationStopping) {
synchronization.cancel()
}
}
@@ -0,0 +1,38 @@
package com.mtusi.messenger.main.worker
import com.mtusi.messenger.main.infrastructure.controllers.health.configureHealthRouting
import com.mtusi.messenger.main.plugins.configureAttachmentCleanup
import com.mtusi.messenger.main.plugins.configureAttachmentWorker
import com.mtusi.messenger.main.plugins.configureContentNegotiation
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.configureJobBroker
import com.mtusi.messenger.main.plugins.configureKoin
import com.mtusi.messenger.main.plugins.configureRequestId
import com.mtusi.messenger.main.plugins.configureStatusPages
import io.ktor.server.application.Application
import io.ktor.server.routing.routing
fun Application.workerModule() {
configureKoin()
configureDatabase()
configureGracefulShutdown()
configureContentNegotiation()
configureDefaultHeaders()
configureInstanceId()
configureRequestId()
configureStatusPages()
configureJobBroker()
configureAttachmentWorker()
configureAttachmentCleanup()
routing {
configureHealthRouting()
}
}
+26
View File
@@ -110,3 +110,29 @@ storage {
accessKeyFile = ${?S3_ACCESS_KEY_ID_FILE}
secretKeyFile = ${?S3_SECRET_ACCESS_KEY_FILE}
}
broker {
host = "localhost"
host = ${?BROKER_HOST}
port = 5672
port = ${?BROKER_PORT}
username = "messenger"
username = ${?BROKER_USER}
password = ${?BROKER_PASSWORD}
passwordFile = ${?BROKER_PASSWORD_FILE}
queue = "attachment.process.v1"
queue = ${?BROKER_QUEUE}
connectionTimeoutMs = 3000
operationTimeoutMs = 8000
}
worker {
concurrency = 1
concurrency = ${?WORKER_CONCURRENCY}
maxAttempts = 5
maxAttempts = ${?JOB_MAX_ATTEMPTS}
timeoutSeconds = 60
timeoutSeconds = ${?JOB_TIMEOUT_SECONDS}
stagingRetentionSeconds = 86400
stagingRetentionSeconds = ${?STAGING_RETENTION_SECONDS}
}
@@ -0,0 +1,29 @@
ALTER TABLE attachments ADD COLUMN status VARCHAR(16) NOT NULL DEFAULT 'ready'
CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
ALTER TABLE attachments ADD COLUMN staging_cleaned BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE attachments ADD COLUMN error_code VARCHAR(64);
ALTER TABLE attachments ADD COLUMN updated_at TIMESTAMPTZ;
UPDATE attachments SET updated_at = created_at;
ALTER TABLE attachments ALTER COLUMN updated_at SET NOT NULL;
CREATE TABLE attachment_variants (
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
name VARCHAR(16) NOT NULL,
content_type VARCHAR(32) NOT NULL,
size_bytes BIGINT NOT NULL CHECK (size_bytes > 0),
width INTEGER NOT NULL CHECK (width > 0),
height INTEGER NOT NULL CHECK (height > 0),
sha256 VARCHAR(64) NOT NULL,
PRIMARY KEY (attachment_id, name)
);
CREATE TABLE attachment_jobs (
id UUID PRIMARY KEY,
attachment_id UUID NOT NULL UNIQUE REFERENCES attachments(id),
pipeline_version INTEGER NOT NULL DEFAULT 1,
attempts INTEGER NOT NULL DEFAULT 0,
lease_token UUID,
lease_until TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL,
CHECK ((lease_token IS NULL) = (lease_until IS NULL))
);
@@ -0,0 +1,3 @@
ALTER TABLE attachment_jobs
ADD COLUMN last_error_code VARCHAR(64),
ADD COLUMN next_attempt_at TIMESTAMPTZ;
@@ -0,0 +1,19 @@
ALTER TABLE attachment_jobs ADD COLUMN legacy_original BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE attachment_jobs ADD COLUMN legacy_dispatch_pending BOOLEAN NOT NULL DEFAULT FALSE;
CREATE INDEX attachment_jobs_legacy_dispatch_idx ON attachment_jobs (created_at, id)
WHERE legacy_dispatch_pending;
INSERT INTO attachment_jobs (id, attachment_id, created_at, legacy_original, legacy_dispatch_pending)
SELECT a.id, a.id, CURRENT_TIMESTAMP, TRUE, TRUE
FROM attachments a
WHERE a.status = 'ready'
AND NOT EXISTS (SELECT 1 FROM attachment_jobs j WHERE j.attachment_id = a.id)
AND NOT EXISTS (
SELECT 1 FROM attachment_variants v WHERE v.attachment_id = a.id AND v.name = 'thumbnail'
);
UPDATE attachments a
SET status = 'queued', error_code = NULL, updated_at = CURRENT_TIMESTAMP, staging_cleaned = FALSE
FROM attachment_jobs j
WHERE j.attachment_id = a.id AND j.legacy_dispatch_pending;
+2
View File
@@ -0,0 +1,2 @@
include "application.conf"
ktor.application.modules = [com.mtusi.messenger.main.worker.WorkerKt.workerModule]
@@ -1,27 +1,53 @@
package com.mtusi.messenger.main.infrastructure.controllers.attachment
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
import com.mtusi.messenger.main.support.*
import com.mtusi.messenger.main.support.TestStorage
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.*
import io.ktor.http.*
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.http.content.OutgoingContent
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import java.util.UUID
import java.util.zip.CRC32
import javax.imageio.ImageIO
import kotlin.test.*
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
class AttachmentControllerTest {
@Test
fun `upload originals ACL message links and idempotency`() = runApp { client ->
val alice = client.register("alice")
val bob = client.register("bob")
val outsider = client.register("outsider")
val chat = client.createChat(alice, "files", listOf(alice.id, bob.id))
for (format in listOf("png", "jpeg")) {
val bytes = image(format)
val upload = client.post("/api/v1/chats/${chat.id}/attachments?filename=photo.$format") {
@@ -29,52 +55,101 @@ class AttachmentControllerTest {
contentType(ContentType.parse("image/$format"))
setBody(bytes)
}
assertEquals(HttpStatusCode.Created, upload.status)
assertEquals(HttpStatusCode.Accepted, upload.status)
val attachment = upload.body<Attachment>()
assertEquals("ready", attachment.status)
assertEquals("queued", attachment.status)
assertEquals(emptyList(), attachment.variants)
assertEquals(bytes.size.toLong(), attachment.sizeBytes)
val ready = client.awaitReady(attachment.id, bob)
assertEquals(listOf("thumbnail"), ready.variants.map { it.name })
val path = "/api/v1/attachments/${attachment.id}"
val download = client.get("$path/content") { auth(bob) }
assertEquals(HttpStatusCode.OK, download.status)
assertContentEquals(bytes, download.body<ByteArray>())
assertEquals(HttpStatusCode.NotFound, client.get(path) { auth(outsider) }.status)
assertEquals(HttpStatusCode.NotFound, client.get("$path/content") { auth(outsider) }.status)
assertEquals(HttpStatusCode.Unauthorized, client.get("$path/content").status)
assertEquals(HttpStatusCode.NotFound, client.get("$path/content?variant=thumbnail") { auth(bob) }.status)
val thumbnail = client.get("$path/content?variant=thumbnail") { auth(bob) }
assertEquals(HttpStatusCode.OK, thumbnail.status)
assertEquals(ContentType.Image.JPEG, thumbnail.contentType()?.withoutParameters())
val thumbnailBytes = thumbnail.body<ByteArray>()
val decoded = withContext(Dispatchers.IO) {
thumbnailBytes.inputStream().use { input ->
ImageIO.read(input)
}
}
val missingVariant = client.get("$path/content?variant=crop") { auth(bob) }
assertEquals(32, decoded.width)
assertEquals(20, decoded.height)
assertEquals(HttpStatusCode.NotFound, missingVariant.status)
val outsiderChat = client.createChat(outsider, "outsider", listOf(outsider.id))
assertEquals(HttpStatusCode.NotFound, client.post("/api/v1/chats/${outsiderChat.id}/messages") {
val rejectedByMembership = client.post("/api/v1/chats/${outsiderChat.id}/messages") {
auth(outsider)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest("", listOf(attachment.id.toString())))
}.status)
setBody(
CreateMessageRequest(
text = "",
attachmentIds = listOf(attachment.id.toString())
)
)
}
assertEquals(HttpStatusCode.NotFound, rejectedByMembership.status)
val key = "file-$format"
suspend fun send(ids: List<String>) = client.post("/api/v1/chats/${chat.id}/messages") {
auth(bob)
idempotencyKey(key)
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest("", ids))
setBody(CreateMessageRequest(text = "", attachmentIds = ids))
}
val first = send(listOf(attachment.id.toString()))
assertEquals(HttpStatusCode.Created, first.status)
val message = first.body<Message>()
assertEquals(listOf(attachment.id), message.attachmentIds)
assertEquals(message, send(listOf(attachment.id.toString())).body<Message>())
val otherChat = client.createChat(bob, "other", listOf(bob.id))
assertEquals(HttpStatusCode.NotFound, client.post("/api/v1/chats/${otherChat.id}/messages") {
val rejectedByChat = client.post("/api/v1/chats/${otherChat.id}/messages") {
auth(bob)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(CreateMessageRequest("", listOf(attachment.id.toString())))
}.status)
setBody(
CreateMessageRequest(
text = "",
attachmentIds = listOf(attachment.id.toString())
)
)
}
assertEquals(HttpStatusCode.NotFound, rejectedByChat.status)
}
}
@Test
fun `invalid images filenames and byte limit return client errors`() = runApp { client ->
val user = client.register("upload")
val chat = client.createChat(user, "files", listOf(user.id))
suspend fun upload(
bytes: ByteArray,
type: String = "image/png",
@@ -86,6 +161,7 @@ class AttachmentControllerTest {
contentType(ContentType.parse(type))
setBody(bytes)
}
val malformedMime = client.post("/api/v1/chats/${chat.id}/attachments?filename=photo.png") {
auth(user)
// Keep the invalid header in raw content so the client does not parse it first.
@@ -96,30 +172,73 @@ class AttachmentControllerTest {
override fun bytes() = image("png")
})
}
assertEquals(HttpStatusCode.BadRequest, malformedMime.status)
assertEquals(HttpStatusCode.UnsupportedMediaType, upload("not an image".toByteArray()).status)
assertEquals(HttpStatusCode.UnsupportedMediaType, upload(image("png"), "image/jpeg").status)
assertEquals(HttpStatusCode.UnsupportedMediaType, upload(image("png").copyOf(40)).status)
for (name in listOf("", " ", "\u2003", "../x.png", "a\\b.png", "a\n.png", "a\u0000.png", "x".repeat(256)))
val corrupt = image("png")
var offset = 8
while (offset + 12 <= corrupt.size) {
val length = ByteBuffer.wrap(corrupt, offset, 4).int
val type = String(corrupt, offset + 4, 4, Charsets.US_ASCII)
if (type == "IDAT") {
corrupt[offset + 8] = 0 // Invalid zlib header, but a correct PNG chunk CRC.
val crc = CRC32().apply {
update(corrupt, offset + 4, length + 4)
}
ByteBuffer.wrap(corrupt, offset + 8 + length, 4)
.putInt(crc.value.toInt())
break
}
offset += length + 12
}
assertEquals(HttpStatusCode.UnsupportedMediaType, upload(corrupt).status)
val invalidNames = listOf(
"",
" ",
"\u2003",
"../x.png",
"a\\b.png",
"a\n.png",
"a\u0000.png",
"x".repeat(256)
)
for (name in invalidNames) {
assertEquals(HttpStatusCode.BadRequest, upload(image("png"), name = name).status)
}
assertEquals(HttpStatusCode.PayloadTooLarge, upload(ByteArray(10 * 1024 * 1024 + 1)).status)
}
@Test
fun `S3 outage fails upload download and readiness without losing the original`() = runApp { client ->
val user = client.register("outage")
val chat = client.createChat(user, "files", listOf(user.id))
val bytes = image("png")
suspend fun upload() = client.post("/api/v1/chats/${chat.id}/attachments?filename=photo.png") {
auth(user)
contentType(ContentType.Image.PNG)
setBody(bytes)
}
val attachment = upload().body<Attachment>()
client.awaitReady(attachment.id, user)
val path = "/api/v1/attachments/${attachment.id}/content"
val container = TestStorage.container
container.dockerClient.pauseContainerCmd(container.containerId).exec()
try {
assertEquals(HttpStatusCode.ServiceUnavailable, upload().status)
assertEquals(HttpStatusCode.ServiceUnavailable, client.get(path) { auth(user) }.status)
@@ -128,10 +247,27 @@ class AttachmentControllerTest {
} finally {
container.dockerClient.unpauseContainerCmd(container.containerId).exec()
}
assertContentEquals(bytes, client.get(path) { auth(user) }.body<ByteArray>())
assertEquals(HttpStatusCode.OK, client.get("/health/ready").status)
}
private suspend fun HttpClient.awaitReady(
id: UUID,
user: TestUser
): Attachment = withTimeout(30.seconds) {
val path = "/api/v1/attachments/$id"
var attachment = get(path) { auth(user) }.body<Attachment>()
while (attachment.status != "ready") {
check(attachment.status != "failed") { "attachment failed: ${attachment.errorCode}" }
delay(50.milliseconds)
attachment = get(path) { auth(user) }.body()
}
attachment
}
private fun image(format: String): ByteArray = ByteArrayOutputStream().use {
ImageIO.write(BufferedImage(32, 20, BufferedImage.TYPE_INT_RGB), format, it)
it.toByteArray()
@@ -0,0 +1,54 @@
package com.mtusi.messenger.main.infrastructure.dto
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNamingStrategy
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonObject
import java.util.UUID
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.time.Clock
class AttachmentJobContractTest {
@OptIn(ExperimentalSerializationApi::class)
@Test
fun `job envelope requires every field mandated by the public schema`() {
val json = Json {
encodeDefaults = true
namingStrategy = JsonNamingStrategy.SnakeCase
}
val job = AttachmentJob(
jobId = UUID.randomUUID(),
attachmentId = UUID.randomUUID(),
createdAt = Clock.System.now()
)
val encoded = json.encodeToString(job)
assertEquals(job, json.decodeFromString<AttachmentJob>(encoded))
val fields = json.parseToJsonElement(encoded).jsonObject
val requiredFields = listOf(
"schema_version",
"job_id",
"type",
"attachment_id",
"pipeline_version",
"attempt",
"created_at"
)
for (key in requiredFields) {
val incomplete = JsonObject(fields.filterKeys { it != key }).toString()
assertFailsWith<SerializationException>("Missing required field: $key") {
json.decodeFromString<AttachmentJob>(incomplete)
}
}
}
}
@@ -1,25 +1,25 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.config.storage.SerialStorageConfig
import com.mtusi.messenger.main.config.worker.SerialWorkerConfig
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.UploadJournalModel
import com.mtusi.messenger.main.infrastructure.repositories.attachment.ExposedAttachmentRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.ExposedUploadJournalRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.ObjectStorageRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.storage.S3ObjectStorageRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.ExposedAttachmentJobRepository
import com.mtusi.messenger.main.infrastructure.repositories.chat.ExposedChatRepository
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.JobBrokerService
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.ObjectStorageService
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.S3ObjectStorageService
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.support.TestStorage
import com.mtusi.messenger.main.support.createChat
import com.mtusi.messenger.main.support.register
import com.mtusi.messenger.main.support.runApp
import com.mtusi.messenger.main.infrastructure.models.attachment.UploadJournalModel
import com.mtusi.messenger.main.utils.exposed.operations.plus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
import org.jetbrains.exposed.v1.jdbc.update
import com.mtusi.messenger.main.utils.computeSha256
import java.awt.image.BufferedImage
import java.io.File
import java.nio.file.Files
@@ -31,23 +31,103 @@ import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.time.Clock
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
import org.jetbrains.exposed.v1.jdbc.update
import org.koin.ktor.ext.get
class AttachmentCleanupTest {
@Test
fun `expired failed attachments lose partially published files`() = runApp(startWorker = false) { client ->
val user = client.register("failed_cleanup")
val chat = client.createChat(
creator = user,
title = "failed cleanup",
memberIds = listOf(user.id)
)
val storage = application.get<ObjectStorageService>()
val cleanup = application.get<AttachmentCleanupService>()
val bytes = byteArrayOf(1, 2, 3)
val attachment = Attachment(
id = UUID.randomUUID(),
chatId = chat.id,
ownerId = user.id,
filename = "partial.png",
contentType = "image/png",
sizeBytes = bytes.size.toLong(),
sha256 = bytes.computeSha256(),
createdAt = Clock.System.now(),
status = "failed",
errorCode = "retry_exhausted"
)
suspendedTransaction {
ExposedAttachmentRepository().create(attachment)
}
storage.put(
id = attachment.id,
bytes = bytes,
contentType = attachment.contentType
)
storage.putThumbnail(id = attachment.id, bytes = bytes)
cleanup.cleanup()
assertContentEquals(bytes, storage.get(attachment.id))
assertContentEquals(bytes, storage.getThumbnail(attachment.id))
suspendedTransaction {
AttachmentModel.update(where = { AttachmentModel.id eq attachment.id }) {
it[updatedAt] = CurrentTimestamp + longLiteral(-90_000)
}
}
cleanup.cleanup()
assertTrue(storage.ready())
assertFailsWith<ApiException> { storage.get(attachment.id) }
assertFailsWith<ApiException> { storage.getThumbnail(attachment.id) }
}
@Test
fun `orphan cleanup respects grace and fences late publishers`() = runApp { client ->
val user = client.register("cleanup")
val chat = client.createChat(user, "cleanup", listOf(user.id))
val journal = ExposedUploadJournalRepository()
val attachments = ExposedAttachmentRepository()
val storage = S3ObjectStorageRepository(SerialStorageConfig(
endpoint = TestStorage.endpoint,
bucket = TestStorage.BUCKET,
accessKey = TestStorage.ACCESS_KEY,
secretKey = TestStorage.SECRET_KEY
))
val cleanup = AttachmentCleanupService(journal, storage)
val storage = S3ObjectStorageService(
SerialStorageConfig(
endpoint = TestStorage.endpoint,
bucket = TestStorage.BUCKET,
accessKey = TestStorage.ACCESS_KEY,
secretKey = TestStorage.SECRET_KEY
)
)
val workerConfig = SerialWorkerConfig()
val cleanup = AttachmentCleanupService(
journalRepository = journal,
objectStorageService = storage,
attachmentRepository = attachments,
config = workerConfig
)
val jobs = ExposedAttachmentJobRepository(attachments)
val broker = application.get<JobBrokerService>()
val file = withContext(Dispatchers.IO) {
Files.createTempFile("cleanup-test-", ".png")
@@ -58,28 +138,78 @@ class AttachmentCleanupTest {
}
var orphanId: UUID? = null
val failingStorage = object : ObjectStorageRepository by storage {
override suspend fun put(id: UUID, file: File, contentType: String) {
storage.put(id, file, contentType)
val failingStorage = object : ObjectStorageService by storage {
override suspend fun putStaging(
id: UUID,
file: File,
contentType: String
) {
storage.putStaging(
id = id,
file = file,
contentType = contentType
)
orphanId = id
error("injected failure after PUT, before metadata COMMIT")
}
}
try {
val failingService = DefaultAttachmentService(journal, attachments, ExposedChatRepository(), failingStorage)
val failingService = DefaultAttachmentService(
journalRepository = journal,
attachmentRepository = attachments,
chatRepository = ExposedChatRepository(),
objectStorageService = failingStorage,
jobRepository = jobs,
jobBrokerService = broker
)
assertFailsWith<IllegalStateException> {
failingService.upload(chat.id, user.id, "file.png", "image/png", file)
failingService.upload(
chatId = chat.id,
actorId = user.id,
filename = "file.png",
contentType = "image/png",
file = file
)
}
val id = requireNotNull(orphanId)
assertEquals(null, suspendedTransaction { attachments.findById(id) })
assertContentEquals(file.readBytes(), storage.get(id))
cleanup.cleanup()
assertContentEquals(file.readBytes(), storage.get(id), "fresh upload must survive grace")
val service = DefaultAttachmentService(journal, attachments, ExposedChatRepository(), storage)
val published = service.upload(chat.id, user.id, "ready.png", "image/png", file)
assertEquals(null, suspendedTransaction { attachments.findById(id) })
assertContentEquals(file.readBytes(), storage.getStaging(id))
cleanup.cleanup()
assertContentEquals(
file.readBytes(),
storage.getStaging(id),
"fresh upload must survive grace"
)
val service = DefaultAttachmentService(
journalRepository = journal,
attachmentRepository = attachments,
chatRepository = ExposedChatRepository(),
objectStorageService = storage,
jobRepository = jobs,
jobBrokerService = broker
)
val published = service.upload(
chatId = chat.id,
actorId = user.id,
filename = "ready.png",
contentType = "image/png",
file = file
)
withTimeout(30.seconds) {
while (suspendedTransaction { attachments.findById(published.id)?.status } != "ready") {
delay(50.milliseconds)
}
}
suspendedTransaction {
UploadJournalModel.update({ UploadJournalModel.id eq id }) {
it[expiresAt] = CurrentTimestamp + longLiteral(-1)
@@ -87,14 +217,22 @@ class AttachmentCleanupTest {
}
}
val unavailableStorage = object : ObjectStorageRepository by storage {
val unavailableStorage = object : ObjectStorageService by storage {
override suspend fun delete(id: UUID) {
error("injected S3 delete outage")
}
}
assertEquals(0, AttachmentCleanupService(journal, unavailableStorage).cleanup())
assertContentEquals(file.readBytes(), storage.get(id))
val unavailableCleanup = AttachmentCleanupService(
journalRepository = journal,
objectStorageService = unavailableStorage,
attachmentRepository = attachments,
config = workerConfig
)
assertEquals(0, unavailableCleanup.cleanup())
assertContentEquals(file.readBytes(), storage.getStaging(id))
suspendedTransaction {
UploadJournalModel.update({ UploadJournalModel.id eq id }) {
it[nextAttemptAt] = CurrentTimestamp + longLiteral(-1)
@@ -102,12 +240,12 @@ class AttachmentCleanupTest {
}
assertTrue(cleanup.cleanup() >= 1)
assertFailsWith<ApiException> { storage.get(id) }
assertFailsWith<ApiException> { storage.getStaging(id) }
assertFalse(suspendedTransaction { journal.lockForCompletion(id) })
assertContentEquals(file.readBytes(), storage.get(published.id))
// A process suspended longer than grace can complete a late PUT, but cannot publish metadata.
storage.put(id, file, "image/png")
storage.putStaging(id, file, "image/png")
suspendedTransaction {
UploadJournalModel.update({ UploadJournalModel.id eq id }) {
it[nextAttemptAt] = CurrentTimestamp + longLiteral(-1)
@@ -115,7 +253,7 @@ class AttachmentCleanupTest {
}
assertTrue(cleanup.cleanup() >= 1)
assertFailsWith<ApiException> { storage.get(id) }
assertFailsWith<ApiException> { storage.getStaging(id) }
assertContentEquals(file.readBytes(), storage.get(published.id))
} finally {
file.delete()
@@ -0,0 +1,471 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.config.worker.SerialWorkerConfig
import com.mtusi.messenger.main.infrastructure.controllers.message.requests.CreateMessageRequest
import com.mtusi.messenger.main.infrastructure.dto.Attachment
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import com.mtusi.messenger.main.infrastructure.dto.Message
import com.mtusi.messenger.main.infrastructure.dto.ProcessedImage
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentJobModel
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.AttachmentJobRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.JobClaim
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.JobBrokerService
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.ObjectStorageService
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.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
import com.mtusi.messenger.main.utils.exposed.operations.plus
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.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.util.UUID
import java.util.concurrent.atomic.AtomicInteger
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.update
import org.koin.ktor.ext.get
class AttachmentPipelineTest {
@Test
fun `stopped worker leaves a durable queued attachment and redelivery preserves its result`() = runApp(startWorker = false) { client ->
val alice = client.register("pipeline")
val bob = client.register("reader")
val chat = client.createChat(
creator = alice,
title = "pipeline",
memberIds = listOf(alice.id, bob.id)
)
val original = image()
val upload = client.post("/api/v1/chats/${chat.id}/attachments?filename=sample.png") {
auth(alice)
contentType(ContentType.Image.PNG)
setBody(original)
}
assertEquals(HttpStatusCode.Accepted, upload.status)
val queued = upload.body<Attachment>()
assertEquals("queued", queued.status)
assertEquals(emptyList(), queued.variants)
assertEquals(null, queued.errorCode)
assertEquals(original.computeSha256(), queued.sha256)
val path = "/api/v1/attachments/${queued.id}"
val metadata = client.get(path) { auth(bob) }.body<Attachment>()
val unavailableOriginal = client.get("$path/content") { auth(bob) }
val unavailableThumbnail = client.get("$path/content?variant=thumbnail") { auth(bob) }
assertEquals("queued", metadata.status)
assertEquals(HttpStatusCode.Conflict, unavailableOriginal.status)
assertEquals(HttpStatusCode.Conflict, unavailableThumbnail.status)
val sent = client.post("/api/v1/chats/${chat.id}/messages") {
auth(alice)
idempotencyKey()
contentType(ContentType.Application.Json)
setBody(
CreateMessageRequest(
text = "",
attachmentIds = listOf(queued.id.toString())
)
)
}
assertEquals(HttpStatusCode.Created, sent.status)
val job = jobFor(queued.id)
val processing = application.get<DefaultAttachmentProcessingService>()
assertTrue(processing.process(job))
val ready = client.get(path) { auth(bob) }.body<Attachment>()
assertEquals("ready", ready.status)
assertEquals(null, ready.errorCode)
val variant = ready.variants.single()
assertEquals("thumbnail", variant.name)
assertEquals("image/jpeg", variant.contentType)
assertEquals(256, variant.width)
assertEquals(160, variant.height)
val thumbnail = client.get("$path/content?variant=thumbnail") { auth(bob) }.body<ByteArray>()
assertEquals(variant.sizeBytes, thumbnail.size.toLong())
assertEquals(variant.sha256, thumbnail.computeSha256())
val decoded = withContext(Dispatchers.IO) {
thumbnail.inputStream().use { input ->
ImageIO.read(input)
}
}
val downloaded = client.get("$path/content") { auth(bob) }.body<ByteArray>()
assertEquals(256, decoded.width)
assertEquals(160, decoded.height)
assertContentEquals(original, downloaded)
assertTrue(
processing.process(job),
"a ready redelivery must be acknowledged without another effect"
)
val replayedMetadata = client.get(path) { auth(bob) }.body<Attachment>()
val replayedThumbnail = client.get("$path/content?variant=thumbnail") { auth(bob) }.body<ByteArray>()
val attempts = suspendedTransaction {
AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.id eq job.jobId)
.single()[AttachmentJobModel.attempts]
}
assertEquals(ready, replayedMetadata)
assertContentEquals(thumbnail, replayedThumbnail)
assertEquals(1, attempts)
}
@Test
fun `attempts are bounded and failed attachments reject content and message links`() = runApp(startWorker = false) { client ->
val user = client.register("attempts")
val chat = client.createChat(
creator = user,
title = "attempts",
memberIds = listOf(user.id)
)
val queued = client.post("/api/v1/chats/${chat.id}/attachments?filename=sample.png") {
auth(user)
contentType(ContentType.Image.PNG)
setBody(image())
}.body<Attachment>()
val path = "/api/v1/attachments/${queued.id}"
val key = UUID.randomUUID().toString()
suspend fun send(key: String) = client.post("/api/v1/chats/${chat.id}/messages") {
auth(user)
idempotencyKey(key)
contentType(ContentType.Application.Json)
setBody(
CreateMessageRequest(
text = "",
attachmentIds = listOf(queued.id.toString())
)
)
}
val sent = send(key)
assertEquals(HttpStatusCode.Created, sent.status)
val message = sent.body<Message>()
val job = jobFor(queued.id)
val jobs = application.get<AttachmentJobRepository>()
val firstToken = UUID.randomUUID()
val firstClaim = suspendedTransaction {
jobs.claim(
job = job,
token = firstToken,
maxAttempts = 2,
leaseSeconds = 60
)
}
val processing = client.get(path) { auth(user) }.body<Attachment>()
val competingClaim = suspendedTransaction {
jobs.claim(
job = job,
token = UUID.randomUUID(),
maxAttempts = 2,
leaseSeconds = 60
)
}
assertEquals(JobClaim.Acquired(1), firstClaim)
assertEquals("processing", processing.status)
assertEquals(JobClaim.Busy, competingClaim)
val terminalFirstAttempt = suspendedTransaction {
jobs.fail(
job = job,
token = firstToken,
errorCode = "storage_unavailable",
permanent = false,
maxAttempts = 2
)
}
val pendingRetry = client.get(path) { auth(user) }.body<Attachment>()
assertFalse(terminalFirstAttempt)
assertEquals("queued", pendingRetry.status)
assertNull(pendingRetry.errorCode)
val pendingJob = suspendedTransaction {
AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.id eq job.jobId)
.single()
}
assertEquals("storage_unavailable", pendingJob[AttachmentJobModel.lastErrorCode])
assertNotNull(pendingJob[AttachmentJobModel.nextAttemptAt])
val retry = job.copy(attempt = 2)
val secondToken = UUID.randomUUID()
val staleClaim = suspendedTransaction {
jobs.claim(
job = job,
token = UUID.randomUUID(),
maxAttempts = 2,
leaseSeconds = 60
)
}
val retryClaim = suspendedTransaction {
jobs.claim(
job = retry,
token = secondToken,
maxAttempts = 2,
leaseSeconds = 60
)
}
assertEquals(JobClaim.Retry(2), staleClaim)
assertEquals(JobClaim.Acquired(2), retryClaim)
val claimedJob = suspendedTransaction {
AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.id eq job.jobId)
.single()
}
assertNull(claimedJob[AttachmentJobModel.nextAttemptAt])
val terminalRetry = suspendedTransaction {
jobs.fail(
job = retry,
token = secondToken,
errorCode = "retry_exhausted",
permanent = false,
maxAttempts = 2
)
}
assertTrue(terminalRetry)
val failed = client.get(path) { auth(user) }.body<Attachment>()
assertEquals("failed", failed.status)
assertEquals("retry_exhausted", failed.errorCode)
assertEquals(emptyList(), failed.variants)
val replay = send(key)
assertEquals(HttpStatusCode.Created, replay.status)
assertEquals(message, replay.body<Message>(), "failure after sending must not invalidate idempotent replay")
val unavailableContent = client.get("$path/content") { auth(user) }
val rejectedMessage = send(UUID.randomUUID().toString())
assertEquals(HttpStatusCode.Conflict, unavailableContent.status)
assertEquals(HttpStatusCode.Conflict, rejectedMessage.status)
assertTrue(application.get<DefaultAttachmentProcessingService>().process(job))
assertEquals(failed, client.get(path) { auth(user) }.body<Attachment>())
}
@Test
fun `busy redelivery lets the next attachment finish before lease expiration`() = runApp(startWorker = false) { client ->
val user = client.register("busyredelivery")
val chat = client.createChat(
creator = user,
title = "busy redelivery",
memberIds = listOf(user.id)
)
suspend fun upload(name: String): Attachment =
client.post("/api/v1/chats/${chat.id}/attachments?filename=$name.png") {
auth(user)
contentType(ContentType.Image.PNG)
setBody(image())
}.body()
val busy = upload("busy")
val busyJob = jobFor(busy.id)
val jobs = application.get<AttachmentJobRepository>()
val claim = suspendedTransaction {
jobs.claim(
job = busyJob,
token = UUID.randomUUID(),
maxAttempts = 5,
leaseSeconds = 60
)
}
assertEquals(JobClaim.Acquired(1), claim)
val next = upload("next")
val broker = application.get<JobBrokerService>()
val worker = application.get<DefaultAttachmentProcessingService>()
suspend fun metadata(attachment: Attachment): Attachment {
return client.get("/api/v1/attachments/${attachment.id}") { auth(user) }
.body()
}
suspend fun awaitReady(attachment: Attachment) {
withTimeout(15.seconds) {
while (metadata(attachment).status != "ready") {
delay(50.milliseconds)
}
}
}
coroutineScope {
val consumer = launch {
broker.consume(worker::process)
}
try {
awaitReady(next)
assertEquals("processing", metadata(busy).status)
suspendedTransaction {
AttachmentJobModel.update(where = { AttachmentJobModel.id eq busyJob.jobId }) {
it[leaseUntil] = CurrentTimestamp + longLiteral(-1)
}
}
awaitReady(busy)
} finally {
consumer.cancelAndJoin()
}
}
}
@Test
fun `worker distinguishes permanent image errors from bounded transient failures`() = runApp(startWorker = false) { client ->
val user = client.register("workererrors")
val chat = client.createChat(
creator = user,
title = "errors",
memberIds = listOf(user.id)
)
for (permanent in listOf(false, true)) {
val queued = client.post("/api/v1/chats/${chat.id}/attachments?filename=sample.png") {
auth(user)
contentType(ContentType.Image.PNG)
setBody(image())
}.body<Attachment>()
val path = "/api/v1/attachments/${queued.id}"
val job = jobFor(queued.id)
val calls = AtomicInteger()
val processor = object : ImageProcessingService {
override suspend fun thumbnail(
bytes: ByteArray,
declaredType: String
): ProcessedImage {
calls.incrementAndGet()
if (permanent) {
throw ApiException(ErrorCode.UNSUPPORTED_MEDIA_TYPE, "invalid image")
}
error("injected temporary processing failure")
}
}
val service = DefaultAttachmentProcessingService(
jobRepository = application.get<AttachmentJobRepository>(),
attachmentRepository = application.get<AttachmentRepository>(),
objectStorageService = application.get<ObjectStorageService>(),
imageProcessingService = processor,
jobBrokerService = application.get<JobBrokerService>(),
config = SerialWorkerConfig(maxAttempts = 2)
)
assertTrue(service.process(job))
if (!permanent) {
val pendingRetry = client.get(path) { auth(user) }.body<Attachment>()
assertEquals("queued", pendingRetry.status)
assertTrue(service.process(job.copy(attempt = 2)))
}
val failed = client.get(path) { auth(user) }.body<Attachment>()
val expectedError = if (permanent) "invalid_image" else "retry_exhausted"
val expectedCalls = if (permanent) 1 else 2
assertEquals("failed", failed.status)
assertEquals(expectedError, failed.errorCode)
assertEquals(expectedCalls, calls.get())
assertTrue(service.process(job))
assertEquals(expectedCalls, calls.get(), "terminal redelivery must not run the processor again")
}
}
private suspend fun jobFor(attachmentId: UUID): AttachmentJob = suspendedTransaction {
val row = AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.attachmentId eq attachmentId)
.single()
AttachmentJob(
jobId = row[AttachmentJobModel.id].value,
attachmentId = attachmentId,
createdAt = row[AttachmentJobModel.createdAt],
pipelineVersion = row[AttachmentJobModel.pipelineVersion]
)
}
private fun image(): ByteArray = ByteArrayOutputStream().use { output ->
ImageIO.write(BufferedImage(320, 200, BufferedImage.TYPE_INT_RGB), "png", output)
output.toByteArray()
}
}
@@ -0,0 +1,284 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.drew.imaging.jpeg.JpegMetadataReader
import com.drew.metadata.exif.ExifIFD0Directory
import com.drew.metadata.exif.ExifReader
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.zip.CRC32
import javax.imageio.ImageIO
import kotlin.math.abs
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ImageProcessingServiceTest {
private val service = DefaultImageProcessingService()
private val colors = listOf(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW)
@Test
fun `thumbnail fits the box floors dimensions and never enlarges the source`() = runBlocking {
val cases = listOf(
Triple(320 to 200, 256 to 160, "png"),
Triple(200 to 320, 160 to 256, "jpeg"),
Triple(501 to 300, 256 to 153, "png"),
Triple(63 to 41, 63 to 41, "jpeg"),
Triple(600 to 1, 256 to 1, "png"),
Triple(1 to 600, 1 to 256, "png")
)
for ((size, expected, format) in cases) {
val source = BufferedImage(size.first, size.second, BufferedImage.TYPE_INT_RGB)
val bytes = encode(source, format)
val original = bytes.copyOf()
val thumbnail = service.thumbnail(bytes, "image/$format")
val decoded = decode(thumbnail.bytes)
assertEquals(expected.first, thumbnail.width)
assertEquals(expected.second, thumbnail.height)
assertEquals(expected.first, decoded.width)
assertEquals(expected.second, decoded.height)
assertEquals("image/jpeg", thumbnail.contentType)
assertEquals(0xff, thumbnail.bytes[0].toInt() and 0xff)
assertEquals(0xd8, thumbnail.bytes[1].toInt() and 0xff)
assertContentEquals(original, bytes, "thumbnail generation must not modify the original")
}
}
@Test
fun `transparent and semitransparent pixels are composited on white`() = runBlocking {
val source = BufferedImage(80, 40, BufferedImage.TYPE_INT_ARGB)
val graphics = source.createGraphics()
try {
graphics.color = Color(255, 0, 0, 128)
graphics.fillRect(0, 0, 40, 40)
} finally {
graphics.dispose()
}
val bytes = encode(source, "png")
val thumbnail = service.thumbnail(bytes, "image/png")
val decoded = decode(thumbnail.bytes)
assertColor(Color.WHITE, Color(decoded.getRGB(60, 20)))
assertColor(Color(255, 127, 127), Color(decoded.getRGB(20, 20)))
assertFalse(decoded.colorModel.hasAlpha())
}
@Test
fun `all JPEG EXIF orientations rotate or mirror pixels and strip orientation from the thumbnail`() = runBlocking {
val encoded = encode(quadrants(), "jpeg")
val expectedCorners = listOf(
listOf(0, 1, 2, 3),
listOf(1, 0, 3, 2),
listOf(3, 2, 1, 0),
listOf(2, 3, 0, 1),
listOf(0, 2, 1, 3),
listOf(2, 0, 3, 1),
listOf(3, 1, 2, 0),
listOf(1, 3, 0, 2)
)
for (orientation in 1..8) {
val bytes = withJpegExif(encoded, orientation)
val original = bytes.copyOf()
val thumbnail = service.thumbnail(bytes, "image/jpeg")
val decoded = decode(thumbnail.bytes)
assertEquals(if (orientation >= 5) 40 else 80, decoded.width)
assertEquals(if (orientation >= 5) 80 else 40, decoded.height)
assertCorners(decoded, expectedCorners[orientation - 1])
assertContentEquals(original, bytes)
val metadata = ByteArrayInputStream(thumbnail.bytes).use {
JpegMetadataReader.readMetadata(it, listOf(ExifReader()))
}
assertNull(metadata.getFirstDirectoryOfType(ExifIFD0Directory::class.java))
}
}
@Test
fun `PNG EXIF orientation is applied before resizing`() = runBlocking {
val source = BufferedImage(320, 200, BufferedImage.TYPE_INT_RGB)
val bytes = withPngExif(encode(source, "png"), 6)
val thumbnail = service.thumbnail(bytes, "image/png")
assertEquals(160, thumbnail.width)
assertEquals(256, thumbnail.height)
val orientedQuadrants = withPngExif(encode(quadrants(), "png"), 7)
val small = service.thumbnail(orientedQuadrants, "image/png")
val decoded = decode(small.bytes)
assertCorners(decoded, listOf(3, 1, 2, 0))
}
@Test
fun `missing or unknown EXIF orientation preserves the normal image`() = runBlocking {
val bytes = encode(quadrants(), "jpeg")
for (original in listOf(bytes, withJpegExif(bytes, 9))) {
val thumbnail = service.thumbnail(original, "image/jpeg")
val decoded = decode(thumbnail.bytes)
assertEquals(80, thumbnail.width)
assertEquals(40, thumbnail.height)
assertCorners(decoded, listOf(0, 1, 2, 3))
}
}
@Test
fun `invalid images and MIME mismatches are rejected before publishing a thumbnail`() = runBlocking {
val invalidImages = listOf(
"not an image".toByteArray() to "image/png",
encode(quadrants(), "png") to "image/jpeg",
encode(quadrants(), "jpeg").copyOf(40) to "image/jpeg"
)
for ((bytes, type) in invalidImages) {
val failure = assertFailsWith<ApiException> {
service.thumbnail(bytes, type)
}
assertEquals(ErrorCode.UNSUPPORTED_MEDIA_TYPE, failure.code)
}
}
private fun quadrants(): BufferedImage {
val image = BufferedImage(80, 40, BufferedImage.TYPE_INT_RGB)
val graphics = image.createGraphics()
try {
colors.forEachIndexed { index, color ->
graphics.color = color
graphics.fillRect((index % 2) * 40, (index / 2) * 20, 40, 20)
}
} finally {
graphics.dispose()
}
return image
}
private fun assertCorners(
image: BufferedImage,
expected: List<Int>
) {
expected.forEachIndexed { index, color ->
val x = if (index % 2 == 0) image.width / 4 else image.width * 3 / 4
val y = if (index / 2 == 0) image.height / 4 else image.height * 3 / 4
assertColor(colors[color], Color(image.getRGB(x, y)))
}
}
private fun assertColor(
expected: Color,
actual: Color
) {
assertTrue(abs(expected.red - actual.red) <= 12, "red: expected $expected, got $actual")
assertTrue(abs(expected.green - actual.green) <= 12, "green: expected $expected, got $actual")
assertTrue(abs(expected.blue - actual.blue) <= 12, "blue: expected $expected, got $actual")
}
private fun encode(
image: BufferedImage,
format: String
): ByteArray = ByteArrayOutputStream().use { output ->
check(ImageIO.write(image, format, output))
output.toByteArray()
}
private suspend fun decode(
bytes: ByteArray
): BufferedImage = withContext(Dispatchers.IO) {
ByteArrayInputStream(bytes).use { input ->
ImageIO.read(input)
}
}
private fun tiff(orientation: Int): ByteArray {
return ByteBuffer.allocate(26)
.order(ByteOrder.LITTLE_ENDIAN)
.put('I'.code.toByte())
.put('I'.code.toByte())
.putShort(42)
.putInt(8)
.putShort(1)
.putShort(0x0112)
.putShort(3)
.putInt(1)
.putShort(orientation.toShort())
.putShort(0)
.putInt(0)
.array()
}
private fun withJpegExif(
bytes: ByteArray,
orientation: Int
): ByteArray {
val exif = byteArrayOf(69, 120, 105, 102, 0, 0) + tiff(orientation)
return ByteArrayOutputStream().use { output ->
output.write(bytes, 0, 2)
DataOutputStream(output).apply {
writeShort(0xffe1)
writeShort(exif.size + 2)
write(exif)
write(bytes, 2, bytes.size - 2)
}
output.toByteArray()
}
}
private fun withPngExif(
bytes: ByteArray,
orientation: Int
): ByteArray {
val type = "eXIf".toByteArray(Charsets.US_ASCII)
val data = tiff(orientation)
val crc = CRC32().apply {
update(type)
update(data)
}
return ByteArrayOutputStream().use { output ->
output.write(bytes, 0, 33)
DataOutputStream(output).apply {
writeInt(data.size)
write(type)
write(data)
writeInt(crc.value.toInt())
write(bytes, 33, bytes.size - 33)
}
output.toByteArray()
}
}
}
@@ -0,0 +1,129 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.config.storage.SerialStorageConfig
import com.mtusi.messenger.main.infrastructure.repositories.attachment.AttachmentRepository
import com.mtusi.messenger.main.infrastructure.services.attachment.storage.S3ObjectStorageService
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.support.TestDatabase
import com.mtusi.messenger.main.support.TestStorage
import com.mtusi.messenger.main.support.runApp
import com.mtusi.messenger.main.utils.computeSha256
import io.ktor.client.request.get
import io.ktor.http.HttpStatusCode
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.flywaydb.core.Flyway
import org.koin.ktor.ext.get
import org.testcontainers.containers.PostgreSQLContainer
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.sql.DriverManager
import java.util.UUID
import javax.imageio.ImageIO
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.time.Duration.Companion.milliseconds
class LegacyAttachmentMigrationTest {
@Test
fun `migration schedules a thumbnail for an existing lab4 original`() {
val id = UUID.randomUUID()
val original = ByteArrayOutputStream().use { output ->
ImageIO.write(BufferedImage(320, 200, BufferedImage.TYPE_INT_RGB), "png", output)
output.toByteArray()
}
TestDatabase.create().use { database ->
database.start()
TestDatabase.awaitConnectable(database)
seedLab4Attachment(database, id, original)
val storage = S3ObjectStorageService(
SerialStorageConfig(
endpoint = TestStorage.endpoint,
bucket = TestStorage.BUCKET,
accessKey = TestStorage.ACCESS_KEY,
secretKey = TestStorage.SECRET_KEY
)
)
runBlocking {
storage.put(
id = id,
bytes = original,
contentType = "image/png"
)
}
runApp(database = database) { client ->
assertEquals(HttpStatusCode.OK, client.get("/health/live").status)
val attachments = application.get<AttachmentRepository>()
val ready = withTimeout(30_000.milliseconds) {
var attachment = suspendedTransaction { checkNotNull(attachments.findById(id)) }
while (attachment.status != "ready") {
check(attachment.status != "failed") { attachment.errorCode.orEmpty() }
delay(50.milliseconds)
attachment = suspendedTransaction { checkNotNull(attachments.findById(id)) }
}
attachment
}
val variant = ready.variants.single()
val thumbnail = storage.getThumbnail(id)
assertContentEquals(original, storage.get(id))
assertEquals("thumbnail", variant.name)
assertEquals(256, variant.width)
assertEquals(160, variant.height)
assertEquals(variant.sha256, thumbnail.computeSha256())
}
}
}
private fun seedLab4Attachment(
database: PostgreSQLContainer<*>,
id: UUID,
original: ByteArray
) {
Flyway.configure()
.dataSource(database.jdbcUrl, database.username, database.password)
.locations("classpath:migrations")
.target("5")
.load()
.migrate()
DriverManager.getConnection(database.jdbcUrl, database.username, database.password).use { connection ->
connection.prepareStatement(
"""
WITH owner AS (
INSERT INTO users VALUES (?, 'legacy', 'Legacy', 'unused', CURRENT_TIMESTAMP)
RETURNING id
), chat AS (
INSERT INTO chats VALUES (?, 'Legacy', CURRENT_TIMESTAMP)
RETURNING id
)
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, created_at)
SELECT ?, chat.id, owner.id, 'legacy.png', 'image/png', ?, ?, CURRENT_TIMESTAMP
FROM owner CROSS JOIN chat
""".trimIndent()
).use { insert ->
insert.setObject(1, UUID.randomUUID())
insert.setObject(2, UUID.randomUUID())
insert.setObject(3, id)
insert.setLong(4, original.size.toLong())
insert.setString(5, original.computeSha256())
assertEquals(1, insert.executeUpdate())
}
}
}
}
@@ -0,0 +1,137 @@
package com.mtusi.messenger.main.infrastructure.services.attachment.jobs
import com.mtusi.messenger.main.config.broker.SerialBrokerConfig
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import com.mtusi.messenger.main.support.TestBroker
import com.rabbitmq.client.ConnectionFactory
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.util.UUID
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Clock
import kotlin.time.Duration.Companion.milliseconds
class RabbitMqJobBrokerServiceTest {
@Test
fun `confirmed job survives broker restart and negative acknowledgement preserves its identity`() = runBlocking {
val config = TestBroker.config().copy(
connectionTimeoutMs = 1000,
operationTimeoutMs = 2000
)
val job = AttachmentJob(
jobId = UUID.randomUUID(),
attachmentId = UUID.randomUUID(),
createdAt = Clock.System.now()
)
val marker = job.copy(
jobId = UUID.randomUUID(),
attachmentId = UUID.randomUUID()
)
val publisher = RabbitMqJobBrokerService(config)
try {
// No producer remains to republish after restart: the next delivery must
// come from the broker's persisted data.
publisher.publish(job)
} finally {
publisher.close()
}
val recoveredConfig = withTimeout(30_000.milliseconds) {
val container = TestBroker.container
val containerId = container.containerId
withContext(Dispatchers.IO) {
container.dockerClient.restartContainerCmd(containerId).exec()
}
assertEquals(containerId, TestBroker.container.containerId)
// Docker may assign another ephemeral host port when the container restarts.
val recoveredConfig = config.copy(port = TestBroker.port)
val broker = RabbitMqJobBrokerService(recoveredConfig)
try {
val firstDelivery = CompletableDeferred<AttachmentJob>()
val redelivery = CompletableDeferred<AttachmentJob>()
val markerDelivery = CompletableDeferred<AttachmentJob>()
val consumer = launch {
broker.consume { delivered ->
when {
delivered.jobId == marker.jobId -> {
markerDelivery.complete(delivered)
awaitCancellation()
}
firstDelivery.complete(delivered) -> false
else -> {
redelivery.complete(delivered)
true
}
}
}
}
try {
assertEquals(job, firstDelivery.await())
assertEquals(job, redelivery.await())
// The marker synchronizes with the receive loop and stays unacknowledged.
broker.publish(marker)
assertEquals(marker, markerDelivery.await())
} finally {
consumer.cancelAndJoin()
}
} finally {
broker.close()
}
recoveredConfig
}
// The closed channel must requeue the marker and only the marker.
assertEquals(
listOf(marker.jobId.toString()),
drainMessageIds(recoveredConfig)
)
}
private suspend fun drainMessageIds(
config: SerialBrokerConfig
): List<String> = withContext(Dispatchers.IO) {
val factory = ConnectionFactory().apply {
host = config.host
port = config.port
username = config.username
password = requireNotNull(config.password)
connectionTimeout = config.connectionTimeoutMs
handshakeTimeout = config.operationTimeoutMs
channelRpcTimeout = config.operationTimeoutMs
}
factory.newConnection().use { connection ->
connection.createChannel().use { channel ->
buildList {
while (true) {
val delivery = channel.basicGet(config.queue, true) ?: break
add(delivery.props.messageId)
}
}
}
}
}
}
@@ -6,6 +6,7 @@ import com.mtusi.messenger.main.infrastructure.controllers.user.requests.CreateU
import com.mtusi.messenger.main.infrastructure.dto.Chat
import com.mtusi.messenger.main.infrastructure.dto.User
import com.mtusi.messenger.main.module
import com.mtusi.messenger.main.plugins.configureAttachmentWorker
import com.typesafe.config.ConfigFactory
import io.ktor.client.HttpClient
import io.ktor.client.call.body
@@ -62,6 +63,12 @@ private fun testConfig(
) = HoconApplicationConfig(
ConfigFactory.parseMap(
mapOf(
"broker.host" to TestBroker.host,
"broker.port" to TestBroker.port,
"broker.username" to TestBroker.USERNAME,
"broker.password" to TestBroker.PASSWORD,
"broker.queue" to "test-${UUID.randomUUID()}",
"storage.endpoint" to TestStorage.endpoint,
"storage.bucket" to TestStorage.BUCKET,
"storage.accessKey" to TestStorage.ACCESS_KEY,
@@ -100,19 +107,35 @@ fun runApp(
redis: RedisEndpoint = TestRedis.endpoint(),
idempotencyTtlSeconds: Long = 86400,
sessionRevokeTimeoutMs: Long = 8000,
startWorker: Boolean = true,
block: suspend ApplicationTestBuilder.(HttpClient) -> Unit
) = testApplication {
environment {
config = testConfig(sessionTtlSeconds, database, databaseConnectionTimeoutMs, redis, idempotencyTtlSeconds, sessionRevokeTimeoutMs)
config = testConfig(
sessionTtlSeconds = sessionTtlSeconds,
database = database,
databaseConnectionTimeoutMs = databaseConnectionTimeoutMs,
redis = redis,
idempotencyTtlSeconds = idempotencyTtlSeconds,
sessionRevokeTimeoutMs = sessionRevokeTimeoutMs
)
}
application {
module()
if (startWorker) {
configureAttachmentWorker()
}
}
val client = createClient {
install(ContentNegotiation) {
json(testJson)
}
}
block(client)
}
@@ -0,0 +1,52 @@
package com.mtusi.messenger.main.support
import com.github.dockerjava.api.model.ExposedPort
import com.mtusi.messenger.main.config.broker.SerialBrokerConfig
import org.testcontainers.containers.GenericContainer
import org.testcontainers.containers.wait.strategy.Wait
import java.util.UUID
object TestBroker {
const val USERNAME = "test-worker"
const val PASSWORD = "test-broker-password"
val container by lazy {
GenericContainer("rabbitmq@sha256:cd4009416f83d7e5895020cd71b0963f3b8a4dfc3de74bbb6fb3bfe5f81f01e0")
.withEnv("RABBITMQ_DEFAULT_USER", USERNAME)
.withEnv("RABBITMQ_DEFAULT_PASS", PASSWORD)
.withExposedPorts(5672)
.waitingFor(Wait.forLogMessage(".*Server startup complete.*\\n", 1))
.also {
it.start()
}
}
val host: String
get() = container.host
val port: Int
get() {
val bindings = container.dockerClient
.inspectContainerCmd(container.containerId)
.exec()
.networkSettings
.ports
.bindings
return bindings.getValue(ExposedPort.tcp(5672))
.first()
.hostPortSpec
.toInt()
}
fun config(queue: String = "attachments-test-${UUID.randomUUID()}"): SerialBrokerConfig {
return SerialBrokerConfig(
host = host,
port = port,
username = USERNAME,
password = PASSWORD,
queue = queue
)
}
}