"""Обработка одного сообщения о задании — то, что делает worker. Шаги и что устойчиво после каждого: 1. захват (`claim_job`): `processing`, аренда, номер попытки. Сообщение не про текущую попытку — no-op, его подтверждают; 2. оригинал из staging (проверяются размер и SHA-256 из строки: доверяем метаданным БД, а не тому, что лежит в S3); 3. варианты в отдельном процессе (`src/renderer.py`); 4. PUT оригинала в конечный ключ и вариантов — ключи детерминированы, повтор перезаписывает тем же; 5. фиксация (`finish_job`): варианты, `ready` — одной транзакцией, пока попытка ещё наша. Сбой между шагами ничего не ломает: объекты без фиксации просто будут перезаписаны следующей попыткой, а после фиксации повтор — no-op. Ошибки делятся на постоянные (файл не обработать — сразу `failed`) и временные (S3, БД, перегрузка — `queued` с backoff и jitter, пока есть попытки). """ import hashlib import random import time from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import timedelta from src.constants import ( ATTACHMENT_MAX_BYTES, ERROR_PROCESSING_FAILED, ERROR_RETRY_EXHAUSTED, ERROR_SOURCE_MISSING, ERROR_TOO_LARGE, VARIANT_FORMATS, ) from src.domain import Attachment, Job, JobMessage, Variant from src.errors import ObjectStorageUnavailable from src.log import get_logger from src.renderer import ImageRenderer, RenderFailed, RenderRejected from src.storage import AttachmentObjects, PipelineStorage from src.storage.base import CLAIMED from src.storage.objects import SourceTooLarge, StoredObjectMissing log = get_logger(__name__) # итоги одной доставки (в журнал и метрики стенда) DONE = "ready" FAILED = "failed" RETRY = "retry" FENCED = "fenced" @dataclass(frozen=True, slots=True) class RetryPolicy: max_attempts: int base: float cap: float def delay(self, attempt: int) -> float: """Экспонента от номера попытки с «равным» jitter: половина детерминирована, половина случайна — повторы разных заданий расходятся, но не схлопываются к нулю.""" ceiling = min(self.cap, self.base * 2 ** max(0, attempt - 1)) return ceiling / 2 + random.uniform(0, ceiling / 2) class _Permanent(Exception): def __init__(self, code: str, detail: str) -> None: super().__init__(detail) self.code = code self.detail = detail class _Transient(Exception): pass class ProcessingService: def __init__( self, pipeline: PipelineStorage, objects: AttachmentObjects, renderer: ImageRenderer, *, lease: timedelta, retry: RetryPolicy, checkpoint: Callable[[str, Job], Awaitable[None]] | None = None, ) -> None: self._pipeline = pipeline self._objects = objects self._renderer = renderer self._lease = lease self._retry = retry self._checkpoint = checkpoint async def handle(self, *, message: JobMessage) -> str: """Итог доставки; исключение — только отказ PostgreSQL на захвате или фиксации исхода (тогда задание вернёт relay по аренде).""" started = time.monotonic() claim = await self._pipeline.claim_job( job_id=message.job_id, attempt=message.attempt, lease=self._lease ) if claim.outcome != CLAIMED: log.info( "job delivery skipped job_id=%s attempt=%d outcome=%s", message.job_id, message.attempt, claim.outcome, ) return claim.outcome job, attachment = claim.job, claim.attachment assert job is not None assert attachment is not None try: variants, peak = await self._process(job, attachment) except _Permanent as exc: await self._fail(job, exc.code, exc.detail) return FAILED except _Transient as exc: return await self._again(job, str(exc)) if self._checkpoint is not None: await self._checkpoint("objects", job) finished = await self._pipeline.finish_job( job_id=job.id, attempt=job.attempt, variants=variants ) if self._checkpoint is not None: await self._checkpoint("commit", job) if not finished: # аренда истекла, и задание уже отдано другой попытке: наши # объекты те же по ключам, фиксировать нечего log.warning("job result fenced job_id=%s attempt=%d", job.id, job.attempt) return FENCED log.info( "attachment processed attachment_id=%s job_id=%s attempt=%d " "variants=%d render_peak_kib=%d took=%.0fms waited=%.0fms", attachment.id, job.id, job.attempt, len(variants), peak, (time.monotonic() - started) * 1000, # от приёма загрузки до захвата этой попытки (job.updated_at - attachment.created_at).total_seconds() * 1000, ) return DONE async def _process( self, job: Job, attachment: Attachment ) -> tuple[list[Variant], int]: if attachment.staging_key is None: raise _Permanent(ERROR_SOURCE_MISSING, "staging_cleared") try: data = await self._objects.read_all( attachment.staging_key, max_bytes=ATTACHMENT_MAX_BYTES ) except StoredObjectMissing: raise _Permanent(ERROR_SOURCE_MISSING, "staging_missing") from None except SourceTooLarge: raise _Permanent(ERROR_TOO_LARGE, "staging_too_large") from None except ObjectStorageUnavailable: raise _Transient("s3_read") from None if ( len(data) != attachment.size_bytes or hashlib.sha256(data).digest() != attachment.sha256 ): raise _Permanent(ERROR_PROCESSING_FAILED, "staging_checksum") try: rendered = await self._renderer.render( data, content_type=attachment.content_type ) except RenderRejected as exc: raise _Permanent(exc.code, "render_rejected") from None except RenderFailed as exc: raise _Transient(exc.reason) from None variants: list[Variant] = [] try: await self._objects.put_bytes( attachment.object_key, data, content_type=attachment.content_type ) for item in rendered.variants: key = self._objects.variant_key(attachment.id, item.name) await self._objects.put_bytes( key, item.data, content_type=item.content_type ) variants.append( Variant( name=item.name, content_type=item.content_type, size_bytes=len(item.data), width=item.width, height=item.height, sha256=hashlib.sha256(item.data).digest(), object_key=key, ) ) except ObjectStorageUnavailable: raise _Transient("s3_write") from None if {v.name for v in variants} != set(VARIANT_FORMATS): raise _Permanent(ERROR_PROCESSING_FAILED, "variants_incomplete") return variants, rendered.peak_rss_kib async def _again(self, job: Job, reason: str) -> str: spent = job.attempt - job.attempt_base if spent >= self._retry.max_attempts: await self._fail(job, ERROR_RETRY_EXHAUSTED, reason) return FAILED delay = self._retry.delay(spent) moved = await self._pipeline.retry_job( job_id=job.id, attempt=job.attempt, delay=timedelta(seconds=delay), error=reason, ) log.info( "job retry scheduled job_id=%s attachment_id=%s attempt=%d " "reason=%s delay=%.1fs fenced=%s", job.id, job.attachment_id, job.attempt, reason, delay, not moved, ) return RETRY if moved else FENCED async def _fail(self, job: Job, code: str, detail: str) -> None: moved = await self._pipeline.fail_job( job_id=job.id, attempt=job.attempt, error_code=code, detail=detail ) log.warning( "attachment processing failed attachment_id=%s job_id=%s attempt=%d " "error_code=%s detail=%s fenced=%s", job.attachment_id, job.id, job.attempt, code, detail, not moved, )