Files
mtusi2026lab4-safronov/src/core/services/attachment.py
T
ricoromaandClaude Opus 5.5 5b42bd2891 feat: compensate failed uploads and clean stale pending attachments
- upload: delete the stored object when ready fails before COMMIT or the
  pending row is gone (503 instead of 500); unknown COMMIT outcome keeps it
- cleaner service (python -m src.cleaner): stale pending rows older than
  grace (900 s, must exceed 17 s live-upload bound) under FOR UPDATE SKIP
  LOCKED, object before row, own S3 user with read/delete only
- shared session_scope for API and cleaner; early_stop process name
- partial index on pending attachments, CREATE INDEX CONCURRENTLY
- s3-bootstrap: cleaner user, policy and checks; make env_setup appends
  missing template variables to an existing .env
- failure checks: cleaner on the failure stand, id-list hook actions,
  five new and three updated tests; driver upload-consistency
- sync upload-consistency deltas into main specs (storage-consistency)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 06:10:37 +03:00

369 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import hashlib
import io
import time
from collections.abc import AsyncIterator, Callable
from contextlib import AbstractAsyncContextManager, AsyncExitStack
from uuid import UUID, uuid4
import anyio.to_thread
from sqlalchemy.ext.asyncio import AsyncSession
from src.core import exceptions
from src.core.repos import attachment as attachment_repo
from src.core.repos import attachment_object as attachment_object_repo
from src.core.services.chat import ChatService
from src.infra.cache import Cache
from src.infra.logger import AbstractLogger, get_logger
from src.infra.s3 import ObjectStorage
from src.schemas import dataclasses
from src.schemas.enums import AttachmentStatus, ImageType
from src.utils.constants import ATTACHMENT_MAX_BYTES, ATTACHMENT_MAX_PIXELS
from src.utils.image import (
DamagedImage,
ImageInfo,
TooManyPixels,
UnsupportedImage,
inspect_image,
)
from src.utils.utc import utcnow
logger: AbstractLogger = get_logger().bind(module="attachment_service")
# Content-Type загрузки: тип без параметров, в нижнем регистре
_ACCEPTED_MEDIA_TYPES = frozenset(image_type.value for image_type in ImageType)
# короткая сессия БД на один шаг: `db_session_scope` слоя API
type DbScope = Callable[[], AbstractAsyncContextManager[AsyncSession]]
def _inspect(data: bytes) -> tuple[ImageInfo, bytes]:
"""Структура изображения и SHA-256 — одним вызовом в потоке."""
info = inspect_image(data, max_pixels=ATTACHMENT_MAX_PIXELS)
return info, hashlib.sha256(data).digest()
class AttachmentService:
"""Вложения: загрузка в S3 с метаданными в PostgreSQL, чтение, отдача.
Сессии на весь запрос нет: каждый шаг с БД — свой короткий
`async with self.db_scope()`, без вложенных, поэтому ни одно
соединение пула не занято передачей тела (design change
`attachments`, решение 5). `filename` в журнал не пишется.
"""
def __init__(
self,
db_scope: DbScope,
cache: Cache,
storage: ObjectStorage,
) -> None:
self.db_scope = db_scope
self.cache = cache
self.storage = storage
async def _require_member(
self,
*,
db_session: AsyncSession,
chat_id: UUID,
user_id: UUID,
) -> None:
await ChatService(
db_session=db_session,
cache=self.cache,
).get_chat_for_member(chat_id=chat_id, user_id=user_id)
async def upload(
self,
*,
chat_id: UUID,
owner_id: UUID,
filename: str,
media_type: str | None,
content_length: int | None,
body: AsyncIterator[bytes],
) -> dataclasses.AttachmentFullDTO:
"""Загрузка оригинала; 201 только после `ready` в БД.
Порядок проверок — спек «Порядок проверок загрузки»: членство
(404), `Content-Type` (415), `Content-Length` (413), затем тело со
счётчиком (413) и содержимое (415 или 413). Порядок записи
(design change `attachments`, решение 1): строка `pending` с
ключом объекта — commit, PUT, `ready` — commit. Отказ S3 или БД
после строки `pending` — 503, строка остаётся до уборщика;
компенсация после записанного объекта — `_mark_ready` (design
change `upload-consistency`, решение 1).
"""
started = time.monotonic()
log = logger.bind(
method="upload",
chat_id=chat_id,
filename_length=len(filename),
)
async with self.db_scope() as db_session:
await self._require_member(
db_session=db_session,
chat_id=chat_id,
user_id=owner_id,
)
if media_type not in _ACCEPTED_MEDIA_TYPES:
log.info("Rejected attachment", reason="type")
raise exceptions.UnsupportedMediaType
if (
content_length is not None
and content_length > ATTACHMENT_MAX_BYTES
):
log.info(
"Rejected attachment",
reason="declared_size",
declared_size=content_length,
)
raise exceptions.PayloadTooLarge
data = await self._read_body(body=body, log=log)
try:
info, sha256 = await anyio.to_thread.run_sync(_inspect, data)
except TooManyPixels as e:
log.info("Rejected attachment", reason="pixels")
raise exceptions.PayloadTooLarge from e
except DamagedImage as e:
log.info("Rejected attachment", reason="damaged")
raise exceptions.UnsupportedMediaType from e
except UnsupportedImage as e:
log.info("Rejected attachment", reason="content")
raise exceptions.UnsupportedMediaType from e
if info.content_type != media_type:
log.info("Rejected attachment", reason="content_mismatch")
raise exceptions.UnsupportedMediaType
attachment_id = uuid4()
now = utcnow()
pending = dataclasses.AttachmentFullDTO(
id=attachment_id,
chat_id=chat_id,
owner_id=owner_id,
filename=filename,
content_type=info.content_type,
size_bytes=len(data),
sha256=sha256,
object_key=attachment_object_repo.original_key(
self.storage,
attachment_id=attachment_id,
),
status=AttachmentStatus.PENDING,
created_at=now,
updated_at=now,
)
async with self.db_scope() as db_session:
await attachment_repo.insert_attachment(
db_session=db_session,
attachment=pending,
)
await db_session.commit()
log = log.bind(attachment_id=attachment_id)
try:
await attachment_object_repo.put_original(
self.storage,
key=pending.object_key,
data=data,
content_type=pending.content_type.value,
)
except Exception:
# объект не трогаем: при замороженном S3 удаление ждало бы ещё
# срок вызова, а тело без ответа сервера не уходит (решение 1)
log.warning("Attachment upload left pending", step="put")
raise
ready = await self._mark_ready(
attachment_id=attachment_id,
object_key=pending.object_key,
log=log,
)
log.info(
"Uploaded attachment",
size_bytes=ready.size_bytes,
content_type=ready.content_type,
width=info.width,
height=info.height,
duration_ms=round((time.monotonic() - started) * 1000),
)
return ready
async def _mark_ready(
self,
*,
attachment_id: UUID,
object_key: str,
log: AbstractLogger,
) -> dataclasses.AttachmentFullDTO:
"""`pending` → `ready` после записанного объекта (решение 1).
Сбой до отправки COMMIT — вложение `ready` не станет: объект
удаляется до ответа (без гарантии), строку убирает уборщик. Сбой
на самом COMMIT — исход неизвестен, объект не трогается. Строки
`pending` уже нет (её убрал уборщик: загрузка пережила grace) —
объект удаляется, ответ 503.
"""
# True — COMMIT ушёл в PostgreSQL, и вложение могло стать ready
commit_sent = False
try:
async with self.db_scope() as db_session:
ready = await attachment_repo.mark_ready(
db_session=db_session,
attachment_id=attachment_id,
updated_at=utcnow(),
)
commit_sent = ready is not None
await db_session.commit()
except Exception:
# CancelledError сюда не попадает: при отмене задачи await
# ненадёжен, остаток убирает уборщик
step = "commit" if commit_sent else "ready"
log.warning("Attachment upload left pending", step=step)
if not commit_sent:
await self._compensate(object_key=object_key, log=log)
raise
if ready is None:
log.error("Pending attachment was removed before ready")
await self._compensate(object_key=object_key, log=log)
raise exceptions.ServiceUnavailable
return ready
async def _compensate(
self,
*,
object_key: str,
log: AbstractLogger,
) -> None:
"""Удалить объект загрузки, которая не станет `ready`; без повторов.
Не удалось — `warning`, исходная ошибка загрузки уходит дальше, а
объект вместе со строкой убирает уборщик.
"""
try:
await attachment_object_repo.delete_original(
self.storage,
key=object_key,
)
except Exception as e:
log.warning(
"Attachment object kept for cleaner",
object_key=object_key,
error_type=type(e).__name__,
)
return
log.info("Deleted attachment object", object_key=object_key)
async def _read_body(
self,
*,
body: AsyncIterator[bytes],
log: AbstractLogger,
) -> bytes:
"""Тело целиком; больше лимита — 413 сразу, без дочитывания.
Блоки копятся в `BytesIO`, а `getvalue()` отдаёт `bytes` над его
же буфером, без копии: в памяти одно тело и блок чтения (спек
«Лимит размера до чтения тела»). Именно `bytes`, а не
`bytearray`: botocore оборачивает тело `PutObject` в `BytesIO`, и
`bytes` он не копирует, а `bytearray` копирует. Рост буфера без
копии в образе даёт `MALLOC_MMAP_THRESHOLD_` (`Dockerfile`;
design, решение 6).
"""
buffer = io.BytesIO()
size = 0
try:
async for chunk in body:
size += len(chunk)
if size > ATTACHMENT_MAX_BYTES:
log.info("Rejected attachment", reason="size", size=size)
raise exceptions.PayloadTooLarge
buffer.write(chunk)
except exceptions.UploadInterrupted:
log.info("Rejected attachment", reason="interrupted")
raise
return buffer.getvalue()
async def get_attachment(
self,
*,
attachment_id: UUID,
user_id: UUID,
) -> dataclasses.AttachmentFullDTO:
"""Готовое вложение для участника его чата; иначе 404.
Нет строки, она `pending` или пользователь не участник —
одинаковый `AttachmentNotFound`.
"""
async with self.db_scope() as db_session:
attachment = await attachment_repo.get_attachment(
db_session=db_session,
attachment_id=attachment_id,
)
if (
attachment is None
or attachment.status != AttachmentStatus.READY
):
raise exceptions.AttachmentNotFound
try:
await self._require_member(
db_session=db_session,
chat_id=attachment.chat_id,
user_id=user_id,
)
except exceptions.ChatNotFound as e:
raise exceptions.AttachmentNotFound from e
return attachment
async def open_content(
self,
*,
attachment_id: UUID,
user_id: UUID,
) -> dataclasses.AttachmentContentDTO:
"""Оригинал потоком из S3 (решение 7).
Отказ S3 — 503 до заголовков ответа. Нет объекта или размер в S3
другой — `error` в журнале и 500; строку сервис не меняет.
"""
attachment = await self.get_attachment(
attachment_id=attachment_id,
user_id=user_id,
)
log = logger.bind(
method="open_content",
attachment_id=attachment_id,
object_key=attachment.object_key,
)
stack = AsyncExitStack()
try:
stored = await stack.enter_async_context(
attachment_object_repo.open_original(
self.storage,
key=attachment.object_key,
),
)
except exceptions.StoredObjectMissing as e:
log.error("Attachment content is missing")
raise exceptions.AttachmentContentMissing from e
if stored.size != attachment.size_bytes:
await stack.aclose()
log.error(
"Attachment content size differs",
size_bytes=attachment.size_bytes,
stored_size=stored.size,
)
raise exceptions.AttachmentContentMissing
async def chunks() -> AsyncIterator[bytes]:
try:
async for chunk in stored.iter_chunks():
yield chunk
finally:
await stack.aclose()
return dataclasses.AttachmentContentDTO(
content_type=attachment.content_type,
size_bytes=attachment.size_bytes,
chunks=chunks(),
close=stack.aclose,
)