Completed for a grade of four

This commit is contained in:
2026-11-19 16:48:52 +03:00
parent 248f8a5cb0
commit be2abbb734
50 changed files with 1831 additions and 532 deletions
@@ -1,5 +1,6 @@
package com.mtusi.messenger.main
import com.mtusi.messenger.main.operator.runAttachmentJobsCommand
import com.mtusi.messenger.main.plugins.authentication.configureAuthentication
import com.mtusi.messenger.main.plugins.configureAttachmentCleanup
import com.mtusi.messenger.main.plugins.configureCallLogging
@@ -29,6 +30,10 @@ fun main(args: Array<String>) {
return migrateDatabase()
}
if (command == "attachment-jobs") {
return runAttachmentJobsCommand(args.drop(1))
}
if (command == "worker") {
val workerArgs = arrayOf(
"-config=worker.conf",
@@ -20,7 +20,9 @@ import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import org.koin.ktor.ext.inject
fun Routing.configureHealthRouting() = route("/health") {
fun Routing.configureHealthRouting(
requireBroker: Boolean = false
) = route("/health") {
get("live") {
call.respond(HttpStatusCode.OK, HealthResponse())
@@ -29,7 +31,7 @@ fun Routing.configureHealthRouting() = route("/health") {
val storage by inject<ObjectStorageService>()
val broker by inject<JobBrokerService>()
// Readiness checks PostgreSQL, S3 and RabbitMQ. Redis has a DB fallback.
// API uploads persist in PostgreSQL and S3. Only the worker requires RabbitMQ.
get("ready") {
// SIGTERM received: leave the balancer's rotation while requests in flight are still being finished.
@@ -69,7 +71,7 @@ fun Routing.configureHealthRouting() = route("/health") {
return@get
}
if (!broker.ready()) {
if (requireBroker && !broker.ready()) {
call.respondError(ErrorCode.UNAVAILABLE, "job broker unavailable")
return@get
}
@@ -13,12 +13,12 @@ object AttachmentJobModel : UUIDTable("attachment_jobs") {
val pipelineVersion = integer("pipeline_version").default(1)
val attempts = integer("attempts").default(0)
val replayBaseAttempt = integer("replay_base_attempt").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)
}
@@ -0,0 +1,18 @@
package com.mtusi.messenger.main.infrastructure.models.attachment
import org.jetbrains.exposed.v1.core.dao.id.java.UUIDTable
import org.jetbrains.exposed.v1.datetime.timestamp
object AttachmentJobReplayModel : UUIDTable("attachment_job_replays") {
val jobId = reference("job_id", AttachmentJobModel)
val operator = varchar("operator", 80)
val previousErrorCode = varchar("previous_error_code", 64)
val attempt = integer("attempt")
val createdAt = timestamp("created_at")
init {
uniqueIndex(jobId, attempt)
}
}
@@ -16,5 +16,6 @@ object AttachmentModel : UUIDTable("attachments") {
val updatedAt = timestamp("updated_at")
val status = varchar("status", 16).default("ready")
val stagingCleaned = bool("staging_cleaned").default(false)
val storageCleanupStarted = bool("storage_cleanup_started").default(false)
val errorCode = varchar("error_code", 64).nullable()
}
@@ -0,0 +1,25 @@
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.CurrentTimestamp
import org.jetbrains.exposed.v1.datetime.timestamp
object AttachmentOutboxModel : UUIDTable("attachment_outbox") {
val jobId = reference("job_id", AttachmentJobModel)
val attempt = integer("attempt")
val availableAt = timestamp("available_at").defaultExpression(CurrentTimestamp)
val leaseToken = javaUUID("lease_token").nullable()
val leaseUntil = timestamp("lease_until").nullable()
init {
index(
customIndexName = "attachment_outbox_due_idx",
isUnique = false,
availableAt,
id
)
}
}
@@ -23,10 +23,6 @@ interface AttachmentRepository {
errorCode: String? = null
)
fun markEnqueueFailed(
id: UUID
)
fun markStagingCleaned(
id: UUID
)
@@ -35,9 +31,14 @@ interface AttachmentRepository {
before: Instant
): List<ExpiredAttachmentStorage>
fun claimExpiredStorage(
attachment: ExpiredAttachmentStorage,
before: Instant
): Boolean
fun publish(
id: UUID,
variant: AttachmentVariant
variants: List<AttachmentVariant>
)
fun attach(
@@ -14,7 +14,7 @@ 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.batchUpsert
import org.jetbrains.exposed.v1.jdbc.select
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.update
@@ -99,20 +99,6 @@ class ExposedAttachmentRepository : AttachmentRepository {
}
}
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
) {
@@ -145,16 +131,16 @@ class ExposedAttachmentRepository : AttachmentRepository {
override fun publish(
id: UUID,
variant: AttachmentVariant
variants: List<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
AttachmentVariantModel.batchUpsert(variants) { variant ->
this[AttachmentVariantModel.attachmentId] = id
this[AttachmentVariantModel.name] = variant.name
this[AttachmentVariantModel.contentType] = variant.contentType
this[AttachmentVariantModel.sizeBytes] = variant.sizeBytes
this[AttachmentVariantModel.width] = variant.width
this[AttachmentVariantModel.height] = variant.height
this[AttachmentVariantModel.sha256] = variant.sha256
}
setState(
@@ -163,6 +149,25 @@ class ExposedAttachmentRepository : AttachmentRepository {
)
}
override fun claimExpiredStorage(
attachment: ExpiredAttachmentStorage,
before: Instant
): Boolean {
val status = if (attachment.failed) "failed" else "ready"
return AttachmentModel.update(
where = {
(AttachmentModel.id eq attachment.id)
.and(AttachmentModel.status eq status)
.and(AttachmentModel.updatedAt less before)
.and(AttachmentModel.stagingCleaned eq false)
}
) {
it[storageCleanupStarted] = true
} == 1
}
override fun attach(
messageId: UUID,
ids: List<UUID>
@@ -3,6 +3,8 @@ 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
import kotlin.time.Duration
import kotlin.time.Instant
interface AttachmentJobRepository {
@@ -14,13 +16,14 @@ interface AttachmentJobRepository {
job: AttachmentJob,
token: UUID,
maxAttempts: Int,
leaseSeconds: Long
leaseSeconds: Long,
retryDelay: (Int) -> Duration = { Duration.ZERO }
): JobClaim
fun complete(
job: AttachmentJob,
token: UUID,
variant: AttachmentVariant
variants: List<AttachmentVariant>
): Boolean
fun fail(
@@ -28,19 +31,39 @@ interface AttachmentJobRepository {
token: UUID,
errorCode: String,
permanent: Boolean,
maxAttempts: Int
maxAttempts: Int,
retryDelay: Duration = Duration.ZERO
): Boolean
fun findPendingLegacyJobs(
fun findFailed(
limit: Int
): List<AttachmentJob>
): List<FailedAttachmentJob>
fun markLegacyJobDispatched(
id: UUID
)
fun replay(
id: UUID,
operator: String
): JobReplayResult
}
data class FailedAttachmentJob(
val jobId: UUID,
val attachmentId: UUID,
val attempts: Int,
val errorCode: String,
val lastErrorCode: String?,
val failedAt: Instant,
val replayable: Boolean
)
enum class JobReplayResult {
QUEUED,
NOT_FOUND,
NOT_FAILED,
PERMANENT_FAILURE,
SOURCE_EXPIRED
}
sealed interface JobClaim {
data object Complete : JobClaim
@@ -53,7 +76,8 @@ sealed interface JobClaim {
data class Acquired(
val attempt: Int,
val legacyOriginal: Boolean = false
val legacyOriginal: Boolean = false,
val attemptInRun: Int = attempt
) : JobClaim
}
@@ -0,0 +1,33 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import java.util.UUID
import kotlin.time.Instant
interface AttachmentOutboxRepository {
fun enqueue(
job: AttachmentJob,
availableAt: Instant = job.createdAt
)
fun claimDue(
token: UUID
): PendingAttachmentPublish?
fun complete(
id: UUID,
token: UUID
)
fun reschedule(
id: UUID,
token: UUID
)
}
data class PendingAttachmentPublish(
val id: UUID,
val job: AttachmentJob
)
@@ -3,16 +3,12 @@ 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.AttachmentJobReplayModel
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
@@ -20,10 +16,14 @@ 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.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
@Single
class ExposedAttachmentJobRepository(
private val attachmentRepository: AttachmentRepository
private val attachmentRepository: AttachmentRepository,
private val outboxRepository: AttachmentOutboxRepository
) : AttachmentJobRepository {
override fun create(
@@ -41,67 +41,81 @@ class ExposedAttachmentJobRepository(
job: AttachmentJob,
token: UUID,
maxAttempts: Int,
leaseSeconds: Long
leaseSeconds: Long,
retryDelay: (Int) -> Duration
): JobClaim {
val row = lock(job) ?: return JobClaim.Complete
val status = AttachmentModel
.select(AttachmentModel.status)
.where(AttachmentModel.id eq job.attachmentId)
.forUpdate()
.single()[AttachmentModel.status]
val attachment = lockAttachment(job.attachmentId)
val status = attachment[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]
val attemptsInRun = attempts - row[AttachmentJobModel.replayBaseAttempt]
val leaseUntil = row[AttachmentJobModel.leaseUntil]
val now = row[CurrentTimestamp]
val nextAttempt = attempts + 1
if (attempts >= maxAttempts) {
attachmentRepository.setState(
id = job.attachmentId,
status = "failed",
errorCode = "retry_exhausted"
if (leaseUntil != null) {
// The delivery for the live claim is the only one that can schedule recovery.
if (job.attempt != attempts) {
return JobClaim.Complete
}
if (leaseUntil > now) {
outboxRepository.enqueue(
job = job,
availableAt = leaseUntil
)
return JobClaim.Busy
}
if (attemptsInRun >= maxAttempts) {
markFailed(
job = job,
cause = "lease_expired",
permanent = false
)
return JobClaim.Complete
}
queueRetry(
job = job.copy(attempt = nextAttempt),
errorCode = "lease_expired",
availableAt = now + retryDelay(attemptsInRun)
)
clearLease(job.jobId)
return JobClaim.Retry(attempt = nextAttempt)
}
// Once an attempt moves on, its old deliveries cannot skip backoff or restart a replay.
val nextAttemptAt = row[AttachmentJobModel.nextAttemptAt]
if (job.attempt != nextAttempt || (nextAttemptAt != null && nextAttemptAt > now)) {
return JobClaim.Complete
}
val nextAttempt = attempts + 1
if (attemptsInRun >= maxAttempts) {
markFailed(
job = job,
cause = row[AttachmentJobModel.lastErrorCode] ?: "retry_exhausted",
permanent = false
)
if (job.attempt != nextAttempt) {
if (row[AttachmentJobModel.leaseToken] != null) {
queueRetry(
id = job.jobId,
attachmentId = job.attachmentId,
errorCode = "lease_expired"
)
}
return JobClaim.Retry(attempt = nextAttempt)
return JobClaim.Complete
}
AttachmentJobModel.update(where = { AttachmentJobModel.id eq job.jobId }) {
it[this.attempts] = nextAttempt
it[leaseToken] = token
it[leaseUntil] = CurrentTimestamp + longLiteral(leaseSeconds)
it[nextAttemptAt] = null
it[this.leaseUntil] = now + leaseSeconds.seconds
it[this.nextAttemptAt] = null
}
attachmentRepository.setState(
@@ -111,14 +125,15 @@ class ExposedAttachmentJobRepository(
return JobClaim.Acquired(
attempt = nextAttempt,
legacyOriginal = row[AttachmentJobModel.legacyOriginal]
legacyOriginal = row[AttachmentJobModel.legacyOriginal],
attemptInRun = attemptsInRun + 1
)
}
override fun complete(
job: AttachmentJob,
token: UUID,
variant: AttachmentVariant
variants: List<AttachmentVariant>
): Boolean {
val row = lock(job) ?: return false
@@ -129,7 +144,7 @@ class ExposedAttachmentJobRepository(
attachmentRepository.publish(
id = job.attachmentId,
variant = variant
variants = variants
)
clearLease(job.jobId)
@@ -142,7 +157,8 @@ class ExposedAttachmentJobRepository(
token: UUID,
errorCode: String,
permanent: Boolean,
maxAttempts: Int
maxAttempts: Int,
retryDelay: Duration
): Boolean {
val row = lock(job) ?: return true
@@ -151,90 +167,181 @@ class ExposedAttachmentJobRepository(
return false
}
val terminal = permanent || row[AttachmentJobModel.attempts] >= maxAttempts
val attempts = row[AttachmentJobModel.attempts]
val attemptsInRun = attempts - row[AttachmentJobModel.replayBaseAttempt]
val terminal = permanent || attemptsInRun >= maxAttempts
if (!terminal) {
queueRetry(
id = job.jobId,
attachmentId = job.attachmentId,
errorCode = errorCode
job = job.copy(attempt = attempts + 1),
errorCode = errorCode,
availableAt = row[CurrentTimestamp] + retryDelay
)
return false
}
markFailed(
job = job,
cause = errorCode,
permanent = permanent
)
return true
}
private fun queueRetry(
job: AttachmentJob,
errorCode: String,
availableAt: Instant
) {
attachmentRepository.setState(
id = job.attachmentId,
status = "failed",
errorCode = if (permanent) errorCode else "retry_exhausted"
status = "queued"
)
AttachmentJobModel.update(where = { AttachmentJobModel.id eq job.jobId }) {
it[leaseToken] = null
it[leaseUntil] = null
it[lastErrorCode] = errorCode
it[nextAttemptAt] = null
it[nextAttemptAt] = availableAt
}
return true
outboxRepository.enqueue(
job = job,
availableAt = availableAt
)
}
private fun queueRetry(
id: UUID,
attachmentId: UUID,
errorCode: String
private fun markFailed(
job: AttachmentJob,
cause: String,
permanent: Boolean
) {
attachmentRepository.setState(
id = job.attachmentId,
status = "failed",
errorCode = if (permanent) cause else "retry_exhausted"
)
AttachmentJobModel.update(where = { AttachmentJobModel.id eq job.jobId }) {
it[leaseToken] = null
it[leaseUntil] = null
it[lastErrorCode] = cause
it[nextAttemptAt] = null
}
}
override fun findFailed(
limit: Int
): List<FailedAttachmentJob> {
return AttachmentJobModel
.innerJoin(AttachmentModel)
.selectAll()
.where(AttachmentModel.status eq "failed")
.orderBy(AttachmentModel.updatedAt to SortOrder.DESC, AttachmentJobModel.id to SortOrder.ASC)
.limit(limit)
.map { row ->
FailedAttachmentJob(
jobId = row[AttachmentJobModel.id].value,
attachmentId = row[AttachmentJobModel.attachmentId].value,
attempts = row[AttachmentJobModel.attempts],
errorCode = checkNotNull(row[AttachmentModel.errorCode]),
lastErrorCode = row[AttachmentJobModel.lastErrorCode],
failedAt = row[AttachmentModel.updatedAt],
replayable = replayRestriction(row) == null
)
}
}
override fun replay(
id: UUID,
operator: String
): JobReplayResult {
val row = lockById(id) ?: return JobReplayResult.NOT_FOUND
val attachmentId = row[AttachmentJobModel.attachmentId].value
val attachment = lockAttachment(attachmentId)
val restriction = replayRestriction(attachment)
if (restriction != null) {
return restriction
}
val attempts = row[AttachmentJobModel.attempts]
val now = row[CurrentTimestamp]
val job = AttachmentJob(
jobId = id,
attachmentId = attachmentId,
createdAt = row[AttachmentJobModel.createdAt],
pipelineVersion = row[AttachmentJobModel.pipelineVersion],
attempt = attempts + 1
)
AttachmentJobModel.update(where = { AttachmentJobModel.id eq id }) {
it[replayBaseAttempt] = attempts
it[leaseToken] = null
it[leaseUntil] = null
it[lastErrorCode] = null
it[nextAttemptAt] = now
}
AttachmentJobReplayModel.insert {
it[jobId] = id
it[this.operator] = operator
it[previousErrorCode] = checkNotNull(attachment[AttachmentModel.errorCode])
it[attempt] = job.attempt
it[createdAt] = now
}
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
}
outboxRepository.enqueue(job, availableAt = now)
return JobReplayResult.QUEUED
}
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 replayRestriction(
attachment: ResultRow
): JobReplayResult? {
return when {
attachment[AttachmentModel.status] != "failed" -> JobReplayResult.NOT_FAILED
attachment[AttachmentModel.errorCode] == "invalid_image" -> JobReplayResult.PERMANENT_FAILURE
attachment[AttachmentModel.stagingCleaned] || attachment[AttachmentModel.storageCleanupStarted] ->
JobReplayResult.SOURCE_EXPIRED
else -> null
}
}
private fun lock(
job: AttachmentJob
): ResultRow? {
return lockById(job.jobId)?.takeIf {
it[AttachmentJobModel.attachmentId].value == job.attachmentId &&
it[AttachmentJobModel.pipelineVersion] == job.pipelineVersion
}
}
private fun lockById(
id: UUID
): ResultRow? {
return AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.id eq job.jobId)
.select(AttachmentJobModel.columns + CurrentTimestamp)
.where(AttachmentJobModel.id eq id)
.forUpdate()
.firstOrNull()
?.takeIf {
it[AttachmentJobModel.attachmentId].value == job.attachmentId &&
it[AttachmentJobModel.pipelineVersion] == job.pipelineVersion
}
}
private fun lockAttachment(
id: UUID
): ResultRow {
return AttachmentModel
.selectAll()
.where(AttachmentModel.id eq id)
.forUpdate()
.single()
}
private fun clearLease(
@@ -0,0 +1,110 @@
package com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs
import com.mtusi.messenger.main.infrastructure.dto.AttachmentJob
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentJobModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentOutboxModel
import com.mtusi.messenger.main.utils.exposed.operations.plus
import org.jetbrains.exposed.v1.core.SortOrder
import org.jetbrains.exposed.v1.core.and
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.isNull
import org.jetbrains.exposed.v1.core.lessEq
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.core.or
import org.jetbrains.exposed.v1.core.vendors.ForUpdateOption
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
import org.jetbrains.exposed.v1.jdbc.deleteWhere
import org.jetbrains.exposed.v1.jdbc.insert
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.update
import org.koin.core.annotation.Single
import java.util.UUID
import kotlin.time.Instant
private const val PUBLISH_LEASE_SECONDS = 30L
private const val PUBLISH_RETRY_SECONDS = 1L
@Single
class ExposedAttachmentOutboxRepository : AttachmentOutboxRepository {
override fun enqueue(
job: AttachmentJob,
availableAt: Instant
) {
AttachmentOutboxModel.insert {
it[jobId] = job.jobId
it[attempt] = job.attempt
it[this.availableAt] = availableAt
}
}
override fun claimDue(
token: UUID
): PendingAttachmentPublish? {
val row = AttachmentOutboxModel
.selectAll()
.where(
(AttachmentOutboxModel.availableAt lessEq CurrentTimestamp) and
(AttachmentOutboxModel.leaseUntil.isNull() or
(AttachmentOutboxModel.leaseUntil lessEq CurrentTimestamp))
)
.orderBy(
AttachmentOutboxModel.availableAt to SortOrder.ASC,
AttachmentOutboxModel.id to SortOrder.ASC
)
.limit(1)
.forUpdate(ForUpdateOption.PostgreSQL.ForUpdate(ForUpdateOption.PostgreSQL.MODE.SKIP_LOCKED))
.firstOrNull()
?: return null
val id = row[AttachmentOutboxModel.id].value
val jobId = row[AttachmentOutboxModel.jobId].value
AttachmentOutboxModel.update(where = { AttachmentOutboxModel.id eq id }) {
it[leaseToken] = token
it[leaseUntil] = CurrentTimestamp + longLiteral(PUBLISH_LEASE_SECONDS)
}
val job = AttachmentJobModel
.selectAll()
.where(AttachmentJobModel.id eq jobId)
.single()
return PendingAttachmentPublish(
id = id,
job = AttachmentJob(
jobId = jobId,
attachmentId = job[AttachmentJobModel.attachmentId].value,
attempt = row[AttachmentOutboxModel.attempt],
pipelineVersion = job[AttachmentJobModel.pipelineVersion],
createdAt = job[AttachmentJobModel.createdAt]
)
)
}
override fun complete(
id: UUID,
token: UUID
) {
AttachmentOutboxModel.deleteWhere {
(AttachmentOutboxModel.id eq id) and (leaseToken eq token)
}
}
override fun reschedule(
id: UUID,
token: UUID
) {
AttachmentOutboxModel.update(
where = {
(AttachmentOutboxModel.id eq id) and (AttachmentOutboxModel.leaseToken eq token)
}
) {
it[availableAt] = CurrentTimestamp + longLiteral(PUBLISH_RETRY_SECONDS)
it[leaseToken] = null
it[leaseUntil] = null
}
}
}
@@ -37,19 +37,27 @@ class AttachmentCleanupService(
}
}
val expired = suspendedTransaction {
attachmentRepository.findExpiredStorage(
before = Clock.System.now() - config.stagingRetentionSeconds.seconds
)
}
val before = Clock.System.now() - config.stagingRetentionSeconds.seconds
val expired = suspendedTransaction { attachmentRepository.findExpiredStorage(before) }
expired.forEach { attachment ->
for (attachment in expired) {
try {
val claimed = suspendedTransaction {
attachmentRepository.claimExpiredStorage(
attachment = attachment,
before = before
)
}
if (!claimed) {
continue
}
when {
attachment.failed && !attachment.legacyOriginal ->
objectStorageService.delete(attachment.id)
attachment.failed ->
objectStorageService.deleteThumbnail(attachment.id)
objectStorageService.deleteVariants(attachment.id)
!attachment.legacyOriginal ->
objectStorageService.deleteStaging(attachment.id)
}
@@ -0,0 +1,137 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import com.mtusi.messenger.main.infrastructure.dto.ProcessedImage
import com.mtusi.messenger.main.infrastructure.types.ApiException
import com.mtusi.messenger.main.infrastructure.types.ErrorCode
import kotlinx.coroutines.runBlocking
import java.io.DataInputStream
import java.io.DataOutputStream
import java.nio.file.Path
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.seconds
private const val INVALID_IMAGE = 64
private const val IMAGE_LIMIT = 65
private const val ENCODER_TIMEOUT = 66
private const val JVM_OUT_OF_MEMORY = 3
private val OUTPUT_TYPES = linkedMapOf(
"thumbnail" to "image/jpeg",
"crop" to "image/jpeg",
"optimized" to "image/webp"
)
internal object AttachmentImageProcessor {
suspend fun process(
bytes: ByteArray,
declaredType: String
): Map<String, ProcessedImage> {
if (bytes.size > MAX_ATTACHMENT_BYTES) {
throw ApiException(
code = ErrorCode.PAYLOAD_TOO_LARGE,
message = "file exceeds 10 MiB"
)
}
val java = Path.of(System.getProperty("java.home"), "bin", "java")
val classpath = System.getProperty("messenger.image.classpath")
?: System.getProperty("java.class.path")
val response = runImageProcess(
command = listOf(
java.toString(),
"-Xmx384m",
"-XX:+UseSerialGC",
"-XX:ActiveProcessorCount=1",
"-XX:+ExitOnOutOfMemoryError",
"-Djava.awt.headless=true",
"-cp", classpath,
AttachmentImageProcessor::class.java.name,
declaredType
),
input = bytes,
outputLimit = MAX_ATTACHMENT_BYTES + 1024 * 1024,
timeout = 25.seconds
)
when (response.exitCode) {
INVALID_IMAGE -> throw ApiException(
code = ErrorCode.UNSUPPORTED_MEDIA_TYPE,
message = "invalid source image"
)
IMAGE_LIMIT, JVM_OUT_OF_MEMORY -> throw ApiException(
code = ErrorCode.PAYLOAD_TOO_LARGE,
message = "image exceeds processing limits"
)
ENCODER_TIMEOUT -> throw ImageProcessTimeoutException()
else -> check(response.exitCode == 0) { "image processor failed" }
}
return readVariants(response.output)
}
@JvmStatic
fun main(
args: Array<String>
) {
val declaredType = args.single()
val bytes = System.`in`.readNBytes(MAX_ATTACHMENT_BYTES + 1)
val variants = try {
runBlocking {
DefaultImageProcessingService().generateVariants(
bytes = bytes,
declaredType = declaredType
)
}
} catch (cause: ApiException) {
when (cause.code) {
ErrorCode.UNSUPPORTED_MEDIA_TYPE -> exitProcess(INVALID_IMAGE)
ErrorCode.PAYLOAD_TOO_LARGE -> exitProcess(IMAGE_LIMIT)
else -> throw cause
}
} catch (_: ImageProcessTimeoutException) {
exitProcess(ENCODER_TIMEOUT)
}
DataOutputStream(System.out).use { output ->
for (name in OUTPUT_TYPES.keys) {
val variant = variants.getValue(name)
output.writeInt(variant.width)
output.writeInt(variant.height)
output.writeInt(variant.bytes.size)
output.write(variant.bytes)
}
}
}
private fun readVariants(
bytes: ByteArray
): Map<String, ProcessedImage> = DataInputStream(bytes.inputStream()).use { input ->
val variants = OUTPUT_TYPES.mapValues { (_, contentType) ->
val width = input.readInt()
val height = input.readInt()
val size = input.readInt()
check(width in 1..1280 && height in 1..1280 && size in 1..MAX_ATTACHMENT_BYTES)
val image = ByteArray(size)
input.readFully(image)
ProcessedImage(
bytes = image,
width = width,
height = height,
contentType = contentType
)
}
check(input.read() == -1) { "unexpected image process output" }
variants
}
}
@@ -6,17 +6,18 @@ 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.random.Random
import kotlin.time.Duration
import kotlin.system.exitProcess
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
@@ -26,7 +27,6 @@ class DefaultAttachmentProcessingService(
private val attachmentRepository: AttachmentRepository,
private val objectStorageService: ObjectStorageService,
private val imageProcessingService: ImageProcessingService,
private val jobBrokerService: JobBrokerService,
private val config: WorkerConfig
) {
@@ -40,28 +40,13 @@ class DefaultAttachmentProcessingService(
job = job,
token = token,
maxAttempts = config.maxAttempts,
leaseSeconds = config.timeoutSeconds + 15
leaseSeconds = config.timeoutSeconds + 15,
retryDelay = ::retryDelay
)
}
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
}
JobClaim.Complete, JobClaim.Busy, is JobClaim.Retry -> return true
is JobClaim.Acquired -> Unit
}
@@ -86,31 +71,37 @@ class DefaultAttachmentProcessingService(
val errorCode = when {
isPermanent -> "invalid_image"
cause is ProcessingTimeoutException -> "processing_timeout"
cause is ProcessingTimeoutException || cause is ImageProcessTimeoutException -> "processing_timeout"
cause is ApiException && cause.code == ErrorCode.UNAVAILABLE -> "storage_unavailable"
else -> "processing_failed"
}
val isTerminal = suspendedTransaction {
suspendedTransaction {
jobRepository.fail(
job = job,
token = token,
errorCode = errorCode,
permanent = isPermanent,
maxAttempts = config.maxAttempts
maxAttempts = config.maxAttempts,
retryDelay = retryDelay(claim.attemptInRun)
)
}
if (!isTerminal) {
jobBrokerService.publish(job.copy(attempt = claim.attempt + 1))
}
return true
}
}
private class ProcessingTimeoutException : RuntimeException()
private fun retryDelay(
attempts: Int
): Duration {
val exponent = (attempts - 1).coerceIn(0, 5)
val upperMillis = (1000L shl exponent).coerceAtMost(30_000L)
return Random.nextLong(upperMillis / 2, upperMillis + 1).milliseconds
}
private suspend fun processAttachment(
job: AttachmentJob,
token: UUID,
@@ -134,11 +125,15 @@ class DefaultAttachmentProcessingService(
)
}
val thumbnail = imageProcessingService.thumbnail(
val images = imageProcessingService.variants(
bytes = bytes,
declaredType = attachment.contentType
)
check(images.keys == setOf("thumbnail", "crop", "optimized")) {
"Image processor did not produce all required variants"
}
if (!legacyOriginal) {
objectStorageService.put(
id = attachment.id,
@@ -147,23 +142,33 @@ class DefaultAttachmentProcessingService(
)
}
objectStorageService.putThumbnail(
id = attachment.id,
bytes = thumbnail.bytes
)
val variants = images.map { (name, image) ->
objectStorageService.putVariant(
id = attachment.id,
name = name,
bytes = image.bytes
)
AttachmentVariant(
name = name,
contentType = image.contentType,
sizeBytes = image.bytes.size.toLong(),
width = image.width,
height = image.height,
sha256 = image.bytes.computeSha256()
)
}
// Enabled only on a disposable worker used by the recovery check.
if (System.getenv("LAB5_TEST_CRASH_AFTER_OBJECTS") == attachment.id.toString()) {
exitProcess(86)
}
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()
)
variants = variants
)
}
}
@@ -5,17 +5,15 @@ 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.UploadJournalRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.AttachmentJobRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.AttachmentOutboxRepository
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
@@ -29,7 +27,7 @@ class DefaultAttachmentService(
private val chatRepository: ChatRepository,
private val objectStorageService: ObjectStorageService,
private val jobRepository: AttachmentJobRepository,
private val jobBrokerService: JobBrokerService
private val outboxRepository: AttachmentOutboxRepository
) : AttachmentService {
override suspend fun requireMember(
@@ -97,37 +95,18 @@ class DefaultAttachmentService(
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)
suspendedTransaction {
if (!journalRepository.lockForCompletion(attachment.id)) {
throw ApiException(
code = ErrorCode.UNAVAILABLE,
message = "upload expired"
)
}
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
attachmentRepository.create(attachment)
jobRepository.create(job)
outboxRepository.enqueue(job)
journalRepository.complete(attachment.id)
}
return attachment
@@ -165,9 +144,12 @@ class DefaultAttachmentService(
)
}
when (variant) {
"original" -> objectStorageService.get(attachment.id)
"thumbnail" -> objectStorageService.getThumbnail(attachment.id)
when {
variant == "original" -> objectStorageService.get(attachment.id)
attachment.variants.any { it.name == variant } -> objectStorageService.getVariant(
id = attachment.id,
name = variant
)
else -> throw ApiException(
code = ErrorCode.NOT_FOUND,
message = "variant not found"
@@ -9,6 +9,8 @@ import com.mtusi.messenger.main.infrastructure.dto.ProcessedImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import org.koin.core.annotation.Single
import java.awt.Color
@@ -18,20 +20,212 @@ import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import javax.imageio.IIOImage
import javax.imageio.ImageIO
import javax.imageio.ImageWriteParam
import javax.imageio.stream.MemoryCacheImageOutputStream
import kotlin.time.Duration.Companion.seconds
private const val THUMBNAIL_SIZE = 256
private const val CROP_SIZE = 128
private const val OPTIMIZED_SIZE = 1280
private const val JPEG_QUALITY = 0.85f
@Single
class DefaultImageProcessingService : ImageProcessingService {
override suspend fun thumbnail(
private val decoder = Semaphore(1)
override suspend fun variants(
bytes: ByteArray,
declaredType: String
): ProcessedImage = withContext(Dispatchers.IO) {
): Map<String, ProcessedImage> = decoder.withPermit {
AttachmentImageProcessor.process(
bytes = bytes,
declaredType = declaredType
)
}
internal suspend fun thumbnail(
bytes: ByteArray,
declaredType: String
): ProcessedImage = withSource(bytes, declaredType, ::thumbnail)
internal suspend fun generateVariants(
bytes: ByteArray,
declaredType: String
): Map<String, ProcessedImage> = withSource(bytes, declaredType) { source ->
linkedMapOf(
"thumbnail" to thumbnail(source),
"crop" to crop(source),
"optimized" to optimized(source)
)
}
private suspend fun thumbnail(
source: SourceImage
): ProcessedImage {
val (width, height) = source.fit(THUMBNAIL_SIZE)
return render(
source = source,
width = width,
height = height,
transform = source.scaleTo(width, height),
contentType = "image/jpeg",
encode = ::encodeJpeg
)
}
private suspend fun crop(
source: SourceImage
): ProcessedImage {
val scale = CROP_SIZE.toDouble() / minOf(source.width, source.height)
val transform = AffineTransform.getTranslateInstance(
(CROP_SIZE - source.width * scale) / 2,
(CROP_SIZE - source.height * scale) / 2
).apply {
scale(scale, scale)
}
return render(
source = source,
width = CROP_SIZE,
height = CROP_SIZE,
transform = transform,
contentType = "image/jpeg",
encode = ::encodeJpeg
)
}
private suspend fun optimized(
source: SourceImage
): ProcessedImage {
val (width, height) = source.fit(OPTIMIZED_SIZE)
return render(
source = source,
width = width,
height = height,
transform = source.scaleTo(width, height),
contentType = "image/webp",
encode = ::encodeWebp
)
}
private suspend fun render(
source: SourceImage,
width: Int,
height: Int,
transform: AffineTransform,
contentType: String,
encode: suspend (BufferedImage) -> ByteArray
): ProcessedImage {
currentCoroutineContext().ensureActive()
val preserveAlpha = contentType == "image/webp"
val imageType = if (preserveAlpha) BufferedImage.TYPE_INT_ARGB else BufferedImage.TYPE_INT_RGB
val rendered = BufferedImage(width, height, imageType)
try {
val graphics = rendered.createGraphics()
try {
if (!preserveAlpha) {
graphics.color = Color.WHITE
graphics.fillRect(0, 0, width, height)
}
graphics.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR
)
graphics.setRenderingHint(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY
)
transform.concatenate(source.orientation)
graphics.drawImage(source.original, transform, null)
} finally {
graphics.dispose()
}
return ProcessedImage(
bytes = encode(rendered),
width = width,
height = height,
contentType = contentType
)
} finally {
rendered.flush()
}
}
private fun encodeJpeg(
image: BufferedImage
): ByteArray {
val output = ByteArrayOutputStream()
val writer = ImageIO.getImageWritersByFormatName("jpeg").next()
try {
MemoryCacheImageOutputStream(output).use { stream ->
writer.output = stream
val parameters = writer.defaultWriteParam.apply {
compressionMode = ImageWriteParam.MODE_EXPLICIT
compressionQuality = JPEG_QUALITY
}
writer.write(null, IIOImage(image, null, null), parameters)
}
} finally {
writer.dispose()
}
return output.toByteArray()
}
private suspend fun encodeWebp(
image: BufferedImage
): ByteArray {
val png = ByteArrayOutputStream()
MemoryCacheImageOutputStream(png).use { output ->
check(ImageIO.write(image, "png", output)) { "PNG encoder is unavailable" }
}
val encoded = runImageProcess(
command = listOf(
"cwebp",
"-quiet",
"-q", "82",
"-m", "4",
"-alpha_q", "100",
"-metadata", "none",
"-o", "-",
"--", "-"
),
input = png.toByteArray(),
outputLimit = MAX_ATTACHMENT_BYTES,
timeout = 15.seconds
)
check(encoded.exitCode == 0 && encoded.output.isNotEmpty()) { "WebP encode failed" }
return encoded.output
}
private suspend fun <R> withSource(
bytes: ByteArray,
declaredType: String,
block: suspend (SourceImage) -> R
): R = withContext(Dispatchers.IO) {
val original = ImageValidator.decode(
bytes = bytes,
declaredType = declaredType
@@ -41,94 +235,57 @@ class DefaultImageProcessingService : ImageProcessingService {
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(
block(
SourceImage(
original = original,
width = if (orientation in 5..8) original.height else original.width,
height = if (orientation in 5..8) original.width else original.height,
orientation = 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
private class SourceImage(
val original: BufferedImage,
val width: Int,
val height: Int,
val orientation: AffineTransform
) {
val graphics = thumbnail.createGraphics()
fun fit(
size: Int
): Pair<Int, Int> {
try {
graphics.color = Color.WHITE
graphics.fillRect(0, 0, thumbnail.width, thumbnail.height)
val longest = maxOf(width, height)
graphics.setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR
)
if (longest <= size) {
return width to height
}
graphics.setRenderingHint(
RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY
)
val scaledWidth = maxOf(1, (width.toLong() * size / longest).toInt())
val scaledHeight = maxOf(1, (height.toLong() * size / longest).toInt())
graphics.drawImage(original, transform, null)
} finally {
graphics.dispose()
return scaledWidth to scaledHeight
}
fun scaleTo(
width: Int,
height: Int
): AffineTransform {
return AffineTransform.getScaleInstance(
width.toDouble() / this.width,
height.toDouble() / this.height
)
}
}
private fun readOrientation(
@@ -0,0 +1,64 @@
package com.mtusi.messenger.main.infrastructure.services.attachment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.future.await
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.TimeUnit
import kotlin.time.Duration
internal class ImageProcessTimeoutException : RuntimeException("image processing deadline exceeded")
internal class ImageProcessResult(
val exitCode: Int,
val output: ByteArray
)
internal suspend fun runImageProcess(
command: List<String>,
input: ByteArray,
outputLimit: Int,
timeout: Duration
): ImageProcessResult = withContext(Dispatchers.IO) {
val process = ProcessBuilder(command)
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start()
coroutineScope {
val writer = async {
process.outputStream.use { it.write(input) }
}
val reader = async {
process.inputStream.use { it.readNBytes(outputLimit + 1) }
}
try {
withTimeoutOrNull(timeout) {
val exitCode = process.onExit().await().exitValue()
val output = reader.await()
writer.await()
check(output.size <= outputLimit) { "image process output exceeded limit" }
ImageProcessResult(
exitCode = exitCode,
output = output
)
} ?: throw ImageProcessTimeoutException()
} finally {
// Kill before the scope joins children that may be waiting on the pipes.
if (process.isAlive) {
process.descendants().use { children ->
children.forEach { it.destroyForcibly() }
}
process.destroyForcibly()
process.waitFor(1, TimeUnit.SECONDS)
}
}
}
}
@@ -4,9 +4,9 @@ import com.mtusi.messenger.main.infrastructure.dto.ProcessedImage
interface ImageProcessingService {
suspend fun thumbnail(
suspend fun variants(
bytes: ByteArray,
declaredType: String
): ProcessedImage
): Map<String, ProcessedImage>
}
@@ -0,0 +1,49 @@
package com.mtusi.messenger.main.infrastructure.services.attachment.jobs
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.AttachmentOutboxRepository
import com.mtusi.messenger.main.plugins.suspendedTransaction
import kotlinx.coroutines.CancellationException
import org.koin.core.annotation.Single
import java.util.UUID
private const val PUBLISH_BATCH_SIZE = 32
@Single
class AttachmentOutboxDispatchService(
private val outboxRepository: AttachmentOutboxRepository,
private val jobBrokerService: JobBrokerService
) {
suspend fun publishPending() {
repeat(PUBLISH_BATCH_SIZE) {
val token = UUID.randomUUID()
val pending = suspendedTransaction {
outboxRepository.claimDue(token)
} ?: return
try {
jobBrokerService.publish(pending.job)
} catch (cause: CancellationException) {
throw cause
} catch (cause: Exception) {
suspendedTransaction {
outboxRepository.reschedule(
id = pending.id,
token = token
)
}
throw cause
}
suspendedTransaction {
outboxRepository.complete(
id = pending.id,
token = token
)
}
}
}
}
@@ -1,28 +0,0 @@
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)
}
}
}
}
@@ -25,16 +25,18 @@ interface ObjectStorageService {
id: UUID
)
suspend fun putThumbnail(
suspend fun putVariant(
id: UUID,
name: String,
bytes: ByteArray
)
suspend fun getThumbnail(
id: UUID
suspend fun getVariant(
id: UUID,
name: String
): ByteArray
suspend fun deleteThumbnail(
suspend fun deleteVariants(
id: UUID
)
@@ -85,29 +85,33 @@ class S3ObjectStorageService(
deleteKey(getStagingKey(id))
}
override suspend fun putThumbnail(
override suspend fun putVariant(
id: UUID,
name: String,
bytes: ByteArray
) {
request {
client.putObject {
bucket = config.bucket
key = getThumbnailKey(id)
key = getVariantKey(id, name)
body = bytes.asByteStream()
contentType = "image/jpeg"
contentType = if (name == "optimized") "image/webp" else "image/jpeg"
contentLength = bytes.size.toLong()
}
}
}
override suspend fun getThumbnail(
id: UUID
): ByteArray = getBytes(getThumbnailKey(id))
override suspend fun getVariant(
id: UUID,
name: String
): ByteArray = getBytes(getVariantKey(id, name))
override suspend fun deleteThumbnail(
override suspend fun deleteVariants(
id: UUID
) {
deleteKey(getThumbnailKey(id))
for (name in listOf("thumbnail", "crop", "optimized")) {
deleteKey(getVariantKey(id, name))
}
}
override suspend fun delete(
@@ -115,7 +119,7 @@ class S3ObjectStorageService(
) {
deleteKey(getObjectKey(id))
deleteStaging(id)
deleteThumbnail(id)
deleteVariants(id)
}
override suspend fun ready(): Boolean {
@@ -173,9 +177,19 @@ class S3ObjectStorageService(
id: UUID
) = "staging/$id"
private fun getThumbnailKey(
id: UUID
) = "variants/$id/v1/thumbnail.jpg"
private fun getVariantKey(
id: UUID,
name: String
): String {
val filename = when (name) {
"thumbnail" -> "thumbnail.jpg"
"crop" -> "crop.jpg"
"optimized" -> "optimized.webp"
else -> error("Unknown attachment variant")
}
return "variants/$id/v1/$filename"
}
private suspend fun <T : Any> request(block: suspend () -> T): T {
return try {
@@ -0,0 +1,105 @@
package com.mtusi.messenger.main.operator
import com.mtusi.messenger.main.config.database.SerialDatabaseConfig
import com.mtusi.messenger.main.infrastructure.repositories.attachment.ExposedAttachmentRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.ExposedAttachmentJobRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.ExposedAttachmentOutboxRepository
import com.mtusi.messenger.main.infrastructure.repositories.attachment.jobs.JobReplayResult
import com.mtusi.messenger.main.plugins.createDataSource
import com.mtusi.messenger.main.plugins.suspendedTransaction
import com.mtusi.messenger.main.plugins.validateDatabaseMigrations
import com.typesafe.config.ConfigFactory
import io.ktor.server.config.HoconApplicationConfig
import io.ktor.server.config.getAs
import kotlinx.coroutines.runBlocking
import org.jetbrains.exposed.v1.core.DatabaseConfig
import org.jetbrains.exposed.v1.jdbc.Database
import java.util.UUID
import kotlin.system.exitProcess
private val operatorPattern = Regex("[A-Za-z0-9_.@-]{1,80}")
fun runAttachmentJobsCommand(
args: List<String>
) {
val subcommand = args.firstOrNull()
val replayJobId = if (subcommand == "replay" && args.size == 3) {
runCatching { UUID.fromString(args[1]) }
.getOrNull()
?.takeIf { it.toString().equals(args[1], ignoreCase = true) }
} else {
null
}
val isList = args == listOf("failed")
val isReplay = replayJobId != null && operatorPattern.matches(args[2])
if (!isList && !isReplay) {
System.err.println("Usage: attachment-jobs failed | attachment-jobs replay JOB_ID OPERATOR")
exitProcess(2)
}
val config = HoconApplicationConfig(ConfigFactory.load())
.property("database")
.getAs<SerialDatabaseConfig>()
val exitCode = config.createDataSource().use { dataSource ->
validateDatabaseMigrations(dataSource)
Database.connect(
datasource = dataSource,
databaseConfig = DatabaseConfig {
defaultMaxAttempts = 1
}
)
val jobs = ExposedAttachmentJobRepository(
attachmentRepository = ExposedAttachmentRepository(),
outboxRepository = ExposedAttachmentOutboxRepository()
)
runBlocking {
if (isList) {
val failed = suspendedTransaction {
jobs.findFailed(limit = 100)
}
println("job_id\tattachment_id\tattempts\terror_code\tlast_error_code\tfailed_at\treplayable")
for (job in failed) {
println(
listOf(
job.jobId,
job.attachmentId,
job.attempts,
job.errorCode,
job.lastErrorCode.orEmpty(),
job.failedAt,
job.replayable
).joinToString("\t")
)
}
0
} else {
val id = checkNotNull(replayJobId)
val result = suspendedTransaction {
jobs.replay(
id = id,
operator = args[2]
)
}
if (result == JobReplayResult.QUEUED) {
println("QUEUED ${id}")
0
} else {
System.err.println("REJECTED ${result.name}")
2
}
}
}
}
if (exitCode != 0) {
exitProcess(exitCode)
}
}
@@ -2,8 +2,8 @@ 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.AttachmentOutboxDispatchService
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
@@ -18,7 +18,7 @@ fun Application.configureAttachmentWorker() {
val broker = get<JobBrokerService>()
val processingService = get<DefaultAttachmentProcessingService>()
val legacyDispatchService = get<LegacyAttachmentDispatchService>()
val dispatchService = get<AttachmentOutboxDispatchService>()
val config = get<WorkerConfig>()
val workers = List(config.concurrency) {
@@ -27,14 +27,14 @@ fun Application.configureAttachmentWorker() {
}
}
val legacyDispatch = launch {
val dispatch = launch {
while (isActive) {
try {
legacyDispatchService.publishPending()
dispatchService.publishPending()
} catch (cause: CancellationException) {
throw cause
} catch (cause: Exception) {
log.warn("Legacy attachment dispatch failed ({}); retrying", cause.javaClass.simpleName)
log.warn("Attachment outbox dispatch failed ({}); retrying", cause.javaClass.simpleName)
}
delay(1.seconds)
@@ -43,7 +43,7 @@ fun Application.configureAttachmentWorker() {
monitor.subscribe(ApplicationStopping) {
workers.forEach { it.cancel() }
legacyDispatch.cancel()
dispatch.cancel()
broker.close()
}
@@ -3,7 +3,9 @@ package com.mtusi.messenger.main.plugins
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.AttachmentJobReplayModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentOutboxModel
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
@@ -65,7 +67,7 @@ fun Application.configureDatabase() {
}
private fun DatabaseConfig.createDataSource(): HikariDataSource {
internal fun DatabaseConfig.createDataSource(): HikariDataSource {
return HikariDataSource(
HikariConfig().apply {
poolName = "messenger"
@@ -126,6 +128,8 @@ private fun generateMigration(description: String) {
AttachmentModel,
AttachmentVariantModel,
AttachmentJobModel,
AttachmentJobReplayModel,
AttachmentOutboxModel,
UploadJournalModel,
MessageAttachmentModel,
UserModel,
@@ -32,7 +32,7 @@ fun Application.workerModule() {
configureAttachmentCleanup()
routing {
configureHealthRouting()
configureHealthRouting(requireBroker = true)
}
}
@@ -0,0 +1,13 @@
ALTER TABLE attachment_jobs
ADD COLUMN replay_base_attempt INTEGER NOT NULL DEFAULT 0
CHECK (replay_base_attempt >= 0 AND replay_base_attempt <= attempts);
CREATE TABLE attachment_job_replays (
id UUID PRIMARY KEY,
job_id UUID NOT NULL REFERENCES attachment_jobs(id),
operator VARCHAR(80) NOT NULL,
previous_error_code VARCHAR(64) NOT NULL,
attempt INTEGER NOT NULL CHECK (attempt > 0),
created_at TIMESTAMPTZ NOT NULL,
UNIQUE (job_id, attempt)
);
@@ -0,0 +1,36 @@
ALTER TABLE attachments ADD COLUMN storage_cleanup_started BOOLEAN NOT NULL DEFAULT FALSE;
-- Reuse existing images when upgrading a level-three deployment.
WITH upgraded_jobs AS (
UPDATE attachment_jobs j
SET legacy_original = TRUE,
replay_base_attempt = j.attempts,
last_error_code = NULL,
next_attempt_at = CURRENT_TIMESTAMP
FROM attachments a
WHERE j.attachment_id = a.id
AND a.status = 'ready'
AND (
SELECT COUNT(*)
FROM attachment_variants v
WHERE v.attachment_id = a.id AND v.name IN ('thumbnail', 'crop', 'optimized')
) < 3
RETURNING j.id, j.attachment_id, j.attempts
), queued_attachments AS (
UPDATE attachments a
SET status = 'queued',
error_code = NULL,
updated_at = CURRENT_TIMESTAMP,
staging_cleaned = FALSE
FROM upgraded_jobs j
WHERE a.id = j.attachment_id
RETURNING a.id
)
INSERT INTO attachment_outbox (id, job_id, attempt)
SELECT gen_random_uuid(), j.id, j.attempts + 1
FROM upgraded_jobs j
JOIN queued_attachments a ON a.id = j.attachment_id;
DELETE FROM attachment_variants v
USING attachments a
WHERE v.attachment_id = a.id AND a.status = 'queued';
@@ -0,0 +1,23 @@
CREATE TABLE attachment_outbox (
id UUID PRIMARY KEY,
job_id UUID NOT NULL REFERENCES attachment_jobs(id),
attempt INTEGER NOT NULL CHECK (attempt > 0),
available_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
lease_token UUID,
lease_until TIMESTAMPTZ,
CHECK ((lease_token IS NULL) = (lease_until IS NULL))
);
CREATE INDEX attachment_outbox_due_idx ON attachment_outbox (available_at, id);
-- Recover both pending lab4 imports and unfinished work already accepted by lab5.
INSERT INTO attachment_outbox (id, job_id, attempt, available_at)
SELECT gen_random_uuid(),
j.id,
CASE WHEN j.lease_until IS NULL THEN j.attempts + 1 ELSE j.attempts END,
GREATEST(CURRENT_TIMESTAMP, j.next_attempt_at, j.lease_until)
FROM attachment_jobs j
JOIN attachments a ON a.id = j.attachment_id
WHERE a.status IN ('queued', 'processing');
ALTER TABLE attachment_jobs DROP COLUMN legacy_dispatch_pending;
@@ -66,7 +66,7 @@ class AttachmentControllerTest {
val ready = client.awaitReady(attachment.id, bob)
assertEquals(listOf("thumbnail"), ready.variants.map { it.name })
assertEquals(setOf("thumbnail", "crop", "optimized"), ready.variants.map { it.name }.toSet())
val path = "/api/v1/attachments/${attachment.id}"
val download = client.get("$path/content") { auth(bob) }
@@ -88,10 +88,16 @@ class AttachmentControllerTest {
ImageIO.read(input)
}
}
val missingVariant = client.get("$path/content?variant=crop") { auth(bob) }
val crop = client.get("$path/content?variant=crop") { auth(bob) }
val optimized = client.get("$path/content?variant=optimized") { auth(bob) }
val missingVariant = client.get("$path/content?variant=unknown") { auth(bob) }
assertEquals(32, decoded.width)
assertEquals(20, decoded.height)
assertEquals(HttpStatusCode.OK, crop.status)
assertEquals(ContentType.Image.JPEG, crop.contentType()?.withoutParameters())
assertEquals(HttpStatusCode.OK, optimized.status)
assertEquals(ContentType.parse("image/webp"), optimized.contentType()?.withoutParameters())
assertEquals(HttpStatusCode.NotFound, missingVariant.status)
val outsiderChat = client.createChat(outsider, "outsider", listOf(outsider.id))
@@ -7,9 +7,9 @@ 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.jobs.AttachmentOutboxRepository
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
@@ -81,12 +81,12 @@ class AttachmentCleanupTest {
bytes = bytes,
contentType = attachment.contentType
)
storage.putThumbnail(id = attachment.id, bytes = bytes)
storage.putVariant(id = attachment.id, name = "thumbnail", bytes = bytes)
cleanup.cleanup()
assertContentEquals(bytes, storage.get(attachment.id))
assertContentEquals(bytes, storage.getThumbnail(attachment.id))
assertContentEquals(bytes, storage.getVariant(attachment.id, "thumbnail"))
suspendedTransaction {
AttachmentModel.update(where = { AttachmentModel.id eq attachment.id }) {
@@ -98,7 +98,7 @@ class AttachmentCleanupTest {
assertTrue(storage.ready())
assertFailsWith<ApiException> { storage.get(attachment.id) }
assertFailsWith<ApiException> { storage.getThumbnail(attachment.id) }
assertFailsWith<ApiException> { storage.getVariant(attachment.id, "thumbnail") }
}
@Test
@@ -126,8 +126,11 @@ class AttachmentCleanupTest {
config = workerConfig
)
val jobs = ExposedAttachmentJobRepository(attachments)
val broker = application.get<JobBrokerService>()
val outbox = application.get<AttachmentOutboxRepository>()
val jobs = ExposedAttachmentJobRepository(
attachmentRepository = attachments,
outboxRepository = outbox
)
val file = withContext(Dispatchers.IO) {
Files.createTempFile("cleanup-test-", ".png")
@@ -162,7 +165,7 @@ class AttachmentCleanupTest {
chatRepository = ExposedChatRepository(),
objectStorageService = failingStorage,
jobRepository = jobs,
jobBrokerService = broker
outboxRepository = outbox
)
assertFailsWith<IllegalStateException> {
@@ -194,7 +197,7 @@ class AttachmentCleanupTest {
chatRepository = ExposedChatRepository(),
objectStorageService = storage,
jobRepository = jobs,
jobBrokerService = broker
outboxRepository = outbox
)
val published = service.upload(
chatId = chat.id,
@@ -7,9 +7,14 @@ 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.models.attachment.AttachmentJobReplayModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentModel
import com.mtusi.messenger.main.infrastructure.models.attachment.AttachmentOutboxModel
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.repositories.attachment.jobs.JobReplayResult
import com.mtusi.messenger.main.infrastructure.services.attachment.jobs.AttachmentOutboxDispatchService
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
@@ -51,8 +56,10 @@ 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.and
import org.jetbrains.exposed.v1.core.longLiteral
import org.jetbrains.exposed.v1.datetime.CurrentTimestamp
import org.jetbrains.exposed.v1.jdbc.select
import org.jetbrains.exposed.v1.jdbc.selectAll
import org.jetbrains.exposed.v1.jdbc.update
import org.koin.ktor.ext.get
@@ -119,7 +126,9 @@ class AttachmentPipelineTest {
assertEquals("ready", ready.status)
assertEquals(null, ready.errorCode)
val variant = ready.variants.single()
assertEquals(setOf("thumbnail", "crop", "optimized"), ready.variants.map { it.name }.toSet())
val variant = ready.variants.single { it.name == "thumbnail" }
assertEquals("thumbnail", variant.name)
assertEquals("image/jpeg", variant.contentType)
@@ -229,7 +238,8 @@ class AttachmentPipelineTest {
token = firstToken,
errorCode = "storage_unavailable",
permanent = false,
maxAttempts = 2
maxAttempts = 2,
retryDelay = 5.seconds
)
}
val pendingRetry = client.get(path) { auth(user) }.body<Attachment>()
@@ -258,7 +268,23 @@ class AttachmentPipelineTest {
leaseSeconds = 60
)
}
val earlyClaim = suspendedTransaction {
jobs.claim(
job = retry,
token = UUID.randomUUID(),
maxAttempts = 2,
leaseSeconds = 60
)
}
assertEquals(JobClaim.Complete, staleClaim)
assertEquals(JobClaim.Complete, earlyClaim)
val retryClaim = suspendedTransaction {
AttachmentJobModel.update(where = { AttachmentJobModel.id eq job.jobId }) {
it[nextAttemptAt] = CurrentTimestamp + longLiteral(-1)
}
jobs.claim(
job = retry,
token = secondToken,
@@ -267,7 +293,6 @@ class AttachmentPipelineTest {
)
}
assertEquals(JobClaim.Retry(2), staleClaim)
assertEquals(JobClaim.Acquired(2), retryClaim)
val claimedJob = suspendedTransaction {
@@ -308,8 +333,53 @@ class AttachmentPipelineTest {
assertEquals(HttpStatusCode.Conflict, unavailableContent.status)
assertEquals(HttpStatusCode.Conflict, rejectedMessage.status)
assertTrue(application.get<DefaultAttachmentProcessingService>().process(job))
val worker = application.get<DefaultAttachmentProcessingService>()
assertTrue(worker.process(job))
assertEquals(failed, client.get(path) { auth(user) }.body<Attachment>())
val failedJob = suspendedTransaction {
jobs.findFailed(limit = 100).single { it.jobId == job.jobId }
}
assertTrue(failedJob.replayable)
assertEquals("retry_exhausted", failedJob.errorCode)
assertEquals(2, failedJob.attempts)
val replayResult = suspendedTransaction { jobs.replay(job.jobId, "integration-test") }
assertEquals(JobReplayResult.QUEUED, replayResult)
assertTrue(worker.process(retry))
assertEquals("queued", client.get(path) { auth(user) }.body<Attachment>().status)
// The new run gets a fresh budget, while the absolute envelope number keeps increasing.
val replayedJob = job.copy(attempt = 3)
val replayToken = UUID.randomUUID()
val replayClaim = suspendedTransaction {
jobs.claim(
job = replayedJob,
token = replayToken,
maxAttempts = 1,
leaseSeconds = 60
)
}
assertEquals(JobClaim.Acquired(3, attemptInRun = 1), replayClaim)
assertEquals(
JobReplayResult.NOT_FAILED,
suspendedTransaction { jobs.replay(job.jobId, "integration-test") }
)
val audit = suspendedTransaction {
AttachmentJobReplayModel
.selectAll()
.where(AttachmentJobReplayModel.jobId eq job.jobId)
.single()
}
assertEquals("integration-test", audit[AttachmentJobReplayModel.operator])
assertEquals(3, audit[AttachmentJobReplayModel.attempt])
assertEquals("retry_exhausted", audit[AttachmentJobReplayModel.previousErrorCode])
}
@Test
@@ -347,6 +417,7 @@ class AttachmentPipelineTest {
val next = upload("next")
val broker = application.get<JobBrokerService>()
val worker = application.get<DefaultAttachmentProcessingService>()
val dispatcher = application.get<AttachmentOutboxDispatchService>()
suspend fun metadata(attachment: Attachment): Attachment {
return client.get("/api/v1/attachments/${attachment.id}") { auth(user) }
@@ -362,6 +433,12 @@ class AttachmentPipelineTest {
}
coroutineScope {
val publisher = launch {
while (true) {
dispatcher.publishPending()
delay(50.milliseconds)
}
}
val consumer = launch {
broker.consume(worker::process)
}
@@ -374,11 +451,20 @@ class AttachmentPipelineTest {
AttachmentJobModel.update(where = { AttachmentJobModel.id eq busyJob.jobId }) {
it[leaseUntil] = CurrentTimestamp + longLiteral(-1)
}
AttachmentOutboxModel.update(
where = {
(AttachmentOutboxModel.jobId eq busyJob.jobId) and
(AttachmentOutboxModel.attempt eq 1)
}
) {
it[availableAt] = CurrentTimestamp + longLiteral(-1)
}
}
awaitReady(busy)
} finally {
consumer.cancelAndJoin()
publisher.cancelAndJoin()
}
}
}
@@ -405,10 +491,10 @@ class AttachmentPipelineTest {
val calls = AtomicInteger()
val processor = object : ImageProcessingService {
override suspend fun thumbnail(
override suspend fun variants(
bytes: ByteArray,
declaredType: String
): ProcessedImage {
): Map<String, ProcessedImage> {
calls.incrementAndGet()
if (permanent) {
@@ -424,16 +510,37 @@ class AttachmentPipelineTest {
attachmentRepository = application.get<AttachmentRepository>(),
objectStorageService = application.get<ObjectStorageService>(),
imageProcessingService = processor,
jobBrokerService = application.get<JobBrokerService>(),
config = SerialWorkerConfig(maxAttempts = 2)
)
val startedAt = suspendedTransaction {
AttachmentJobModel
.select(CurrentTimestamp)
.where(AttachmentJobModel.id eq job.jobId)
.single()[CurrentTimestamp]
}
assertTrue(service.process(job))
if (!permanent) {
val pendingRetry = client.get(path) { auth(user) }.body<Attachment>()
assertEquals("queued", pendingRetry.status)
val availableAt = suspendedTransaction {
AttachmentJobModel
.select(AttachmentJobModel.nextAttemptAt)
.where(AttachmentJobModel.id eq job.jobId)
.single()[AttachmentJobModel.nextAttemptAt]
}
assertTrue(assertNotNull(availableAt) >= startedAt + 500.milliseconds)
// Advance the stored deadline instead of waiting on wall clock in the test.
suspendedTransaction {
AttachmentJobModel.update(where = { AttachmentJobModel.id eq job.jobId }) {
it[nextAttemptAt] = CurrentTimestamp + longLiteral(-1)
}
}
assertTrue(service.process(job.copy(attempt = 2)))
}
@@ -447,6 +554,24 @@ class AttachmentPipelineTest {
assertTrue(service.process(job))
assertEquals(expectedCalls, calls.get(), "terminal redelivery must not run the processor again")
val jobs = application.get<AttachmentJobRepository>()
if (permanent) {
assertEquals(
JobReplayResult.PERMANENT_FAILURE,
suspendedTransaction { jobs.replay(job.jobId, "integration-test") }
)
} else {
val replay = suspendedTransaction {
AttachmentModel.update(where = { AttachmentModel.id eq queued.id }) {
it[storageCleanupStarted] = true
}
jobs.replay(job.jobId, "integration-test")
}
assertEquals(JobReplayResult.SOURCE_EXPIRED, replay)
}
}
}
@@ -25,12 +25,102 @@ import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
class ImageProcessingServiceTest {
private val service = DefaultImageProcessingService()
private val colors = listOf(Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW)
@Test
fun `published variants apply orientation and preserve the centered crop`() = runBlocking {
val source = BufferedImage(1600, 800, BufferedImage.TYPE_INT_RGB)
val graphics = source.createGraphics()
try {
graphics.color = Color.RED
graphics.fillRect(0, 0, 400, 800)
graphics.color = Color.GREEN
graphics.fillRect(400, 0, 800, 800)
graphics.color = Color.BLUE
graphics.fillRect(1200, 0, 400, 800)
} finally {
graphics.dispose()
}
val bytes = withPngExif(encode(source, "png"), 6)
val variants = service.variants(bytes, "image/png")
assertEquals(setOf("thumbnail", "crop", "optimized"), variants.keys)
assertEquals(128 to 256, variants.getValue("thumbnail").let { it.width to it.height })
val crop = variants.getValue("crop")
val decodedCrop = decode(crop.bytes)
assertEquals("image/jpeg", crop.contentType)
assertEquals(128 to 128, decodedCrop.width to decodedCrop.height)
assertColor(Color.GREEN, Color(decodedCrop.getRGB(8, 8)))
assertColor(Color.GREEN, Color(decodedCrop.getRGB(120, 120)))
val optimized = variants.getValue("optimized")
val decodedOptimized = decodeWebp(optimized.bytes)
assertEquals("image/webp", optimized.contentType)
assertEquals(640 to 1280, optimized.width to optimized.height)
assertEquals(640 to 1280, decodedOptimized.width to decodedOptimized.height)
assertColor(Color.RED, Color(decodedOptimized.getRGB(250, 100)))
assertColor(Color.GREEN, Color(decodedOptimized.getRGB(250, 640)))
assertColor(Color.BLUE, Color(decodedOptimized.getRGB(250, 1180)))
assertFalse(webpChunks(optimized.bytes).any { it in setOf("EXIF", "XMP ", "ICCP") })
}
@Test
fun `optimized WebP preserves alpha and never enlarges a small source`() = 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 optimized = service.variants(encode(source, "png"), "image/png").getValue("optimized")
val decoded = decodeWebp(optimized.bytes)
assertEquals(80 to 40, optimized.width to optimized.height)
assertEquals(80 to 40, decoded.width to decoded.height)
assertEquals(128, Color(decoded.getRGB(20, 20), true).alpha)
assertEquals(0, Color(decoded.getRGB(60, 20), true).alpha)
}
@Test
fun `worker subprocess preserves permanent image failures`() = runBlocking {
val invalidImage = assertFailsWith<ApiException> {
service.variants("not an image".toByteArray(), "image/png")
}
assertEquals(ErrorCode.UNSUPPORTED_MEDIA_TYPE, invalidImage.code)
}
@Test
fun `image subprocess stops at its deadline`() = runBlocking<Unit> {
assertFailsWith<ImageProcessTimeoutException> {
runImageProcess(
command = listOf("sleep", "10"),
input = ByteArray(0),
outputLimit = 16,
timeout = 100.milliseconds
)
}
}
@Test
fun `thumbnail fits the box floors dimensions and never enlarges the source`() = runBlocking {
@@ -222,6 +312,46 @@ class ImageProcessingServiceTest {
}
}
private suspend fun decodeWebp(
bytes: ByteArray
): BufferedImage {
val decoded = runImageProcess(
command = listOf("dwebp", "-quiet", "-o", "-", "--", "-"),
input = bytes,
outputLimit = MAX_ATTACHMENT_BYTES,
timeout = 10.seconds
)
assertEquals(0, decoded.exitCode)
return decode(decoded.output)
}
private fun webpChunks(
bytes: ByteArray
): List<String> {
assertEquals("RIFF", String(bytes, 0, 4, Charsets.US_ASCII))
assertEquals("WEBP", String(bytes, 8, 4, Charsets.US_ASCII))
return buildList {
var offset = 12
while (offset < bytes.size) {
add(String(bytes, offset, 4, Charsets.US_ASCII))
val size = ByteBuffer.wrap(bytes, offset + 4, 4)
.order(ByteOrder.LITTLE_ENDIAN)
.int
offset += 8 + size + (size and 1)
}
assertEquals(bytes.size, offset)
}
}
private fun tiff(orientation: Int): ByteArray {
return ByteBuffer.allocate(26)
.order(ByteOrder.LITTLE_ENDIAN)
@@ -75,8 +75,8 @@ class LegacyAttachmentMigrationTest {
attachment
}
val variant = ready.variants.single()
val thumbnail = storage.getThumbnail(id)
val variant = ready.variants.single { it.name == "thumbnail" }
val thumbnail = storage.getVariant(id = id, name = "thumbnail")
assertContentEquals(original, storage.get(id))
assertEquals("thumbnail", variant.name)