Files
mtusi2026lab4/src/messenger/attachments/application/handlers.py
T
ArtyomandClaude Opus 5.5 0e4eb1738c Compensate failed uploads and sweep abandoned intents
When the ready commit fails after the object was written, the upload
handler now locks the row, keeps it if it turned out ready, and
otherwise deletes the object first and the pending row second before
answering 503. A ready update that touches no row means the intent was
already swept, so it fails as unavailable and the object goes too;
a 201 without a row cannot happen.

Every worker runs an UploadSweeper that every 30 s removes pending
intents older than UPLOAD_GRACE_SECONDS (900 s, at least 60 s) one row
at a time under FOR UPDATE SKIP LOCKED over the partial pending index,
object first, and logs an audit event for each discard. Bodies are
buffered only inside one of UPLOAD_CONCURRENCY slots per worker and
released before the ready commit, and a client that disconnects in the
middle of a body becomes a 400 instead of an unhandled 500.

The tests run against a throwaway PostgreSQL: a trigger rejects the
ready commit and the compensation leaves neither row nor object, a
row removed during the write gives 503, a failed write stays until the
grace ends, fresh intents and an aged ready attachment in a message
survive a sweep, two concurrent sweeps share five intents exactly, the
background loop runs by itself, a second upload waits for the slot
without reading its body, and aborted and stalled bodies leave nothing.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
2026-10-28 22:39:51 +03:00

151 lines
5.0 KiB
Python

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