feat: process attachments asynchronously with RabbitMQ and a worker

Upload answers 202 after staging, a queued job in PostgreSQL and a broker
confirm; a separate worker publishes the original and a thumbnail with
bounded retries. Adds the job and variant tables, the broker service, the
worker S3 user, cleanup and reconcile support for staging and variants,
the failure stand with broker and worker, bench and driver updates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 06:48:20 +03:00
co-authored by Claude Opus 5.5
parent 40c709a78b
commit ff1a83b6ff
107 changed files with 9765 additions and 993 deletions
+175 -9
View File
@@ -2,7 +2,12 @@
Строка пишется в статусе `pending` до записи объекта и переводится в
`ready` после неё (design change `attachments`, решение 1). Видимость
`pending` решает сервис: repo отдаёт строку как есть. Незавершённые
`pending` решает сервис: repo отдаёт строку как есть. С лабы 5 (design
change `async-attachments`, решения 1–3) `pending` становится `queued`
вместе с заданием, а `processing`, `ready` и `failed` ставит worker;
`updated_at` пишется через `greatest`: часы консольного API и worker
расходятся, а CHECK `updated_at >= created_at` иначе ронял бы запись.
Незавершённые
загрузки выбирает, блокирует, помечает и удаляет уборщик (design change
`upload-consistency`, решение 3). Сверка bucket и БД выбирает строки
страницы списка S3 и строки `ready`, помечает потерянный оригинал
@@ -11,7 +16,7 @@
"""
from collections.abc import Collection
from datetime import datetime
from datetime import datetime, timedelta
from uuid import UUID
from sqlalchemy import (
@@ -23,6 +28,7 @@ from sqlalchemy import (
any_,
bindparam,
delete,
func,
insert,
literal,
or_,
@@ -36,7 +42,11 @@ from sqlalchemy.types import TypeEngine
from src.infra.db.models import Attachment
from src.schemas import dataclasses
from src.schemas.enums import AttachmentStatus, ImageType
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentStatus,
ImageType,
)
_ATTACHMENT_COLUMNS = (
Attachment.id,
@@ -51,6 +61,8 @@ _ATTACHMENT_COLUMNS = (
Attachment.created_at,
Attachment.updated_at,
Attachment.lost_at,
Attachment.staging_key,
Attachment.error_code,
)
@@ -58,9 +70,15 @@ def _to_dto(row: Row) -> dataclasses.AttachmentFullDTO:
fields = dict(row._mapping)
fields["content_type"] = ImageType(fields["content_type"])
fields["status"] = AttachmentStatus(fields["status"])
if fields["error_code"] is not None:
fields["error_code"] = AttachmentErrorCode(fields["error_code"])
return dataclasses.AttachmentFullDTO(**fields)
def _later_of_now(now: datetime) -> ColumnElement[datetime]:
return func.greatest(now, Attachment.updated_at)
async def insert_attachment(
db_session: AsyncSession,
*,
@@ -77,6 +95,7 @@ async def insert_attachment(
size_bytes=attachment.size_bytes,
sha256=attachment.sha256,
object_key=attachment.object_key,
staging_key=attachment.staging_key,
status=attachment.status.value,
created_at=attachment.created_at,
updated_at=attachment.updated_at,
@@ -85,19 +104,20 @@ async def insert_attachment(
return attachment
async def mark_ready(
async def mark_queued(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> dataclasses.AttachmentFullDTO | None:
"""`pending` → `ready`; `None` — строки `pending` нет или уборщик уже
"""`pending` → `queued`; `None` — строки `pending` нет или уборщик уже
пометил её к уборке.
Вставка пишет `created_at` и `updated_at` одним значением, а уборщик
до удаления объекта сдвигает `updated_at` (`mark_removing`): `ready`
до удаления объекта сдвигает `updated_at` (`mark_removing`): `queued`
становится только непомеченная строка (design change
`upload-consistency`, «Уточнения apply», п. 16).
`upload-consistency`, «Уточнения apply», п. 16). `updated_at` растёт:
строка, вернувшаяся в `pending` отменой, больше не переводится.
"""
statement = (
update(Attachment)
@@ -106,13 +126,154 @@ async def mark_ready(
Attachment.status == AttachmentStatus.PENDING.value,
Attachment.updated_at == Attachment.created_at,
)
.values(status=AttachmentStatus.READY.value, updated_at=updated_at)
.values(
status=AttachmentStatus.QUEUED.value,
updated_at=_later_of_now(updated_at),
)
.returning(*_ATTACHMENT_COLUMNS)
)
row = (await db_session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def return_to_pending(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""Отмена приёма: `queued` → `pending`, брокер не подтвердил задание.
`updated_at` строго растёт, поэтому строка не равна `created_at`: для
`mark_queued` и уборщика она уже помечена, объект и саму строку убирает
уборщик (design change `async-attachments`, решение 3).
"""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.QUEUED.value,
)
.values(
status=AttachmentStatus.PENDING.value,
updated_at=func.greatest(
updated_at,
Attachment.updated_at + timedelta(microseconds=1),
),
)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def mark_processing(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""`queued` или `processing` (прежняя попытка потеряна) → `processing`.
`ready` и `failed` не трогаются; `False` — условие не выполнено."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status.in_(
(
AttachmentStatus.QUEUED.value,
AttachmentStatus.PROCESSING.value,
),
),
)
.values(
status=AttachmentStatus.PROCESSING.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def return_to_queued(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""Временная ошибка: `processing` → `queued`."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.PROCESSING.value,
)
.values(
status=AttachmentStatus.QUEUED.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def commit_ready(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""`queued` или `processing` → `ready`; `False` — итог уже есть: готовое
вложение не откатывается и не меняет `updated_at`."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status.in_(
(
AttachmentStatus.QUEUED.value,
AttachmentStatus.PROCESSING.value,
),
),
)
.values(
status=AttachmentStatus.READY.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def commit_failed(
db_session: AsyncSession,
*,
attachment_id: UUID,
error_code: AttachmentErrorCode,
updated_at: datetime,
) -> bool:
"""`queued` или `processing` → `failed` с кодом; `False` — итог уже
есть."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status.in_(
(
AttachmentStatus.QUEUED.value,
AttachmentStatus.PROCESSING.value,
),
),
)
.values(
status=AttachmentStatus.FAILED.value,
error_code=error_code.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def get_attachment(
db_session: AsyncSession,
*,
@@ -141,7 +302,12 @@ async def get_attachments(
# незавершённые загрузки для уборщика (design change upload-consistency,
# решение 3): условия совпадают с частичным индексом
# ix_attachments_pending_created_at
_STALE_COLUMNS = (Attachment.id, Attachment.object_key, Attachment.created_at)
_STALE_COLUMNS = (
Attachment.id,
Attachment.object_key,
Attachment.created_at,
Attachment.staging_key,
)
def _stale_pending(older_than: datetime) -> tuple[ColumnElement[bool], ...]: