import asyncio from collections.abc import AsyncIterator from hashlib import sha256 from messenger.attachments.application.commands import SweepAbandonedUploads, UploadAttachment from messenger.attachments.application.ports import ( AttachmentsUnitOfWork, ChatMembership, ImageInspector, ObjectStorage, ) from messenger.attachments.domain.errors import ChatNotFound, PayloadTooLarge from messenger.attachments.domain.models import Attachment, AttachmentStatus from messenger.attachments.domain.values import Filename, ImageKind from messenger.shared.application.ports import Clock, IdGenerator, Logger class UploadSlots(asyncio.Semaphore): pass async def read_limited(body: AsyncIterator[bytes], limit: int) -> tuple[bytes, str]: chunks: list[bytes] = [] digest = sha256() size = 0 async for chunk in body: size += len(chunk) if size > limit: raise PayloadTooLarge(f"тело больше {limit} байт") digest.update(chunk) chunks.append(chunk) return b"".join(chunks), digest.hexdigest() async def drop( uow: AttachmentsUnitOfWork, storage: ObjectStorage, attachment: Attachment, reason: str ) -> None: await storage.delete(attachment.object_key) attachment.discard(reason) await uow.attachments.remove(attachment) await uow.commit() class UploadAttachmentHandler: __slots__ = ( "_clock", "_ids", "_images", "_limit", "_logger", "_membership", "_slots", "_storage", "_uow", ) def __init__( self, uow: AttachmentsUnitOfWork, membership: ChatMembership, images: ImageInspector, storage: ObjectStorage, *, clock: Clock, ids: IdGenerator, limit: int, slots: UploadSlots, logger: Logger, ) -> None: self._uow = uow self._membership = membership self._images = images self._storage = storage self._clock = clock self._ids = ids self._limit = limit self._slots = slots self._logger = logger async def __call__(self, command: UploadAttachment) -> Attachment: if not await self._membership.is_member(command.chat_id, command.owner_id): raise ChatNotFound("чат не найден") filename = Filename(command.filename or "") declared = ImageKind.declared(command.content_type) async with self._slots: attachment = await self._write(command, filename, declared) attachment.store(self._clock.now()) try: async with self._uow.transaction(): await self._uow.attachments.save(attachment) await self._uow.commit() except Exception: await self._compensate(attachment) raise return attachment async def _write( self, command: UploadAttachment, filename: Filename, declared: ImageKind ) -> Attachment: data, digest = await read_limited(command.body, self._limit) image = await self._images.inspect(data, declared) attachment = Attachment.stage( attachment_id=self._ids.new_id(), chat_id=command.chat_id, owner_id=command.owner_id, filename=filename, image=image, size_bytes=len(data), sha256=digest, now=self._clock.now(), ) async with self._uow.transaction(): await self._uow.attachments.add(attachment) await self._uow.commit() await self._storage.put(attachment.object_key, data, attachment.content_type) return attachment async def _compensate(self, staged: Attachment) -> None: try: async with self._uow.transaction(): current = await self._uow.attachments.lock(staged.id) if current is None: await self._storage.delete(staged.object_key) elif current.status is AttachmentStatus.PENDING: await drop(self._uow, self._storage, current, "compensation") except Exception as error: self._logger.warning( "attachment.compensation_failed", attachment_id=str(staged.id), error=type(error).__name__, ) class SweepAbandonedUploadsHandler: __slots__ = ("_clock", "_storage", "_uow") def __init__(self, uow: AttachmentsUnitOfWork, storage: ObjectStorage, clock: Clock) -> None: self._uow = uow self._storage = storage self._clock = clock async def __call__(self, command: SweepAbandonedUploads) -> int: before = self._clock.now() - command.grace for swept in range(command.limit): async with self._uow.transaction(): abandoned = await self._uow.attachments.next_abandoned(before) if abandoned is None: return swept await drop(self._uow, self._storage, abandoned, "abandoned") return command.limit