included rabbitmq as broker

This commit is contained in:
2026-11-10 07:01:17 +03:00
parent 0a70358829
commit 2b9fb3f375
49 changed files with 3072 additions and 287 deletions
+36 -19
View File
@@ -13,6 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.request_capacity import RequestCapacity
from app.domain.chats import ensure_chat_member
from app.domain.attachment_jobs import enqueue_attachment_job
from app.domain.images import validate_filename, validate_image
from app.errors.exceptions import (
conflict,
@@ -28,7 +29,7 @@ from app.errors.handlers import (
log_recoverable_error,
operation_timeout,
)
from app.schemas.attachment import Attachment
from app.schemas.attachment import Attachment, VARIANT_FILENAMES
from app.schemas.user import User
from app.storage import attachments as repository
from app.storage.s3 import MinioStorage
@@ -151,7 +152,7 @@ async def recover_upload(
await session.rollback()
async def publish_original(
async def stage_attachment(
session: AsyncSession,
storage: MinioStorage,
user: User,
@@ -161,8 +162,9 @@ async def publish_original(
filename: str,
content_type: str,
) -> Attachment:
"""Сохранить исходник в staging и атомарно принять metadata/job."""
id = uuid4()
key = f"originals/{uuid4().hex}"
key = f"staging/{uuid4().hex}"
# Журнал устойчив до PUT, включая аварию процесса и неоднозначный COMMIT.
await repository.reserve_upload(session, id, key)
await session.commit()
@@ -181,13 +183,16 @@ async def publish_original(
id=id,
chat_id=chat_id,
owner_id=user.id,
object_key=key,
object_key=f"originals/{id.hex}/v1",
status="queued",
filename=filename,
content_type=content_type,
size_bytes=original.size_bytes,
sha256=original.sha256,
)
await enqueue_attachment_job(session, id, key)
await repository.finish_upload(session, id)
# Снимок queued строится до COMMIT, даже если worker очень быстрый.
result = Attachment.model_validate(record)
await session.commit()
except BaseException:
@@ -223,7 +228,7 @@ async def upload_attachment(
settings.chunk_bytes,
)
await validate_image(original.path, content_type, settings)
result = await publish_original(
result = await stage_attachment(
session,
storage,
user,
@@ -245,6 +250,13 @@ async def get_attachment(
return Attachment.model_validate(record)
@dataclass(frozen=True)
class DownloadInfo:
filename: str
content_type: str
size_bytes: int
async def download_attachment(
session: AsyncSession,
storage: MinioStorage | None,
@@ -252,25 +264,30 @@ async def download_attachment(
attachment_id: UUID,
*,
variant: str = "original",
) -> tuple[Attachment, AsyncIterator[bytes]]:
) -> tuple[DownloadInfo, AsyncIterator[bytes]]:
result = await get_attachment(session, user, attachment_id)
if variant != "original":
raise not_found()
if result.status != "ready":
raise conflict("Вложение пока недоступно для скачивания")
storage = require_storage(storage)
record = await repository.get_attachment(session, attachment_id)
if record is None:
raise not_found()
key = record.object_key
if variant == "original":
key = record.object_key
info = DownloadInfo(result.filename, result.content_type, result.size_bytes)
else:
selected = next((item for item in result.variants if item.name == variant), None)
keys = {"thumbnail": record.thumbnail_key, "crop": record.crop_key, "optimized": record.optimized_key}
key = keys.get(variant)
if selected is None or key is None:
raise not_found()
info = DownloadInfo(VARIANT_FILENAMES[variant], selected.content_type, selected.size_bytes)
await session.rollback()
info = await storage.stat_object(key)
if (
info is None
or info.size_bytes != result.size_bytes
or info.content_type != result.content_type
):
raise unavailable("Оригинал временно недоступен")
stored = await storage.stat_object(key)
if stored.size_bytes != info.size_bytes or stored.content_type != info.content_type:
raise unavailable("Файл временно недоступен")
stream = await storage.open_object(key)
return result, stream
return info, stream
async def validate_message_attachments(
@@ -283,8 +300,8 @@ async def validate_message_attachments(
records = await repository.get_for_chat(session, chat_id, attachment_ids)
if len(records) != len(attachment_ids):
raise not_found()
if any(record.status != "ready" for record in records):
raise conflict("Вложение ещё не готово")
if any(record.status == "failed" for record in records):
raise conflict("Обработка вложения завершилась ошибкой")
async def reconcile_attachments(