forked from mtusi2026/mtusi2026lab2
Upload now stages the checked original under staging/, and one transaction moves the intent to queued, inserts the job (pipeline version 1, attempt 1), its outbox row and an audit event; the 202 is the in-memory snapshot, never a reread. Content answers 409 until the attachment is ready, the thumbnail variant is served from the published version and absent variants are 404. The relay publishes outbox rows through FastStream with publisher confirms, mandatory routing and persistent delivery, marks a row only after the broker acked it, returns jobs whose lease expired and deletes the staging object of ready attachments. The worker consumes the quorum queue through a FastStream subscriber that declares nothing, takes prefetch from WORKER_CONCURRENCY and acks manually after the result commit, rejects messages off jobs.schema.json to the dead letter exchange and requeues after an infrastructure error. A job is claimed under a lease token; the original is copied to originals/ and a 256 px JPEG thumbnail is written under a content-addressed key; the commit is fenced by the token, inserts variants with ON CONFLICT DO NOTHING and publishes only a newer pipeline version. A transient error reschedules the same job with an exponential delay and a new outbox row, the last attempt fails with retry_exhausted, an undecodable image fails at once with invalid_image, and a redelivered finished job is a recorded no-op. The worker and the relay are assembled in worker.py and relay.py with the dishka FastStream integration and the platform providers of the API; the shared core imports neither FastStream nor aio-pika. Tests cover the thumbnail geometry and rendering, the job message against the contract, the pipeline against PostgreSQL (duplicates, parallel copies, retries, the attempt bound, leases and fencing) and the broker adapters against a throwaway RabbitMQ with the stand's topology and permissions. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
58 lines
2.3 KiB
Python
58 lines
2.3 KiB
Python
from uuid import UUID
|
|
|
|
from messenger.attachments.application.errors import ObjectMissingError
|
|
from messenger.attachments.application.ports import (
|
|
AttachmentDirectory,
|
|
ChatMembership,
|
|
ObjectContent,
|
|
ObjectStorage,
|
|
)
|
|
from messenger.attachments.domain.errors import AttachmentNotFound, AttachmentNotReady
|
|
from messenger.attachments.domain.models import Attachment
|
|
from messenger.shared.application.ports import Logger
|
|
|
|
ORIGINAL = "original"
|
|
|
|
|
|
class GetAttachment:
|
|
__slots__ = ("_attachments", "_membership")
|
|
|
|
def __init__(self, attachments: AttachmentDirectory, membership: ChatMembership) -> None:
|
|
self._attachments = attachments
|
|
self._membership = membership
|
|
|
|
async def __call__(self, attachment_id: UUID, user_id: UUID) -> Attachment:
|
|
attachment = await self._attachments.visible(attachment_id)
|
|
if attachment is None or not await self._membership.is_member(attachment.chat_id, user_id):
|
|
raise AttachmentNotFound("вложение не найдено")
|
|
return attachment
|
|
|
|
|
|
class OpenAttachment:
|
|
__slots__ = ("_get", "_logger", "_storage")
|
|
|
|
def __init__(self, get: GetAttachment, storage: ObjectStorage, logger: Logger) -> None:
|
|
self._get = get
|
|
self._storage = storage
|
|
self._logger = logger
|
|
|
|
async def __call__(
|
|
self, attachment_id: UUID, user_id: UUID, variant: str = ORIGINAL
|
|
) -> tuple[str, ObjectContent]:
|
|
attachment = await self._get(attachment_id, user_id)
|
|
if not attachment.ready:
|
|
raise AttachmentNotReady("вложение ещё не обработано или обработка не удалась")
|
|
if variant == ORIGINAL:
|
|
key, content_type = attachment.original_key, attachment.content_type
|
|
else:
|
|
found = attachment.variant(variant)
|
|
if found is None:
|
|
raise AttachmentNotFound("у вложения нет такого варианта")
|
|
key, content_type = found.object_key, found.content_type
|
|
try:
|
|
content = await self._storage.open(str(key))
|
|
except ObjectMissingError as error:
|
|
self._logger.warning("attachment.object_missing", attachment_id=str(attachment.id))
|
|
raise AttachmentNotFound("вложение не найдено") from error
|
|
return content_type, content
|