feat: add job outbox, relay, leases and image variants to the pipeline

Move publishing out of the upload path: a relay process publishes queued
jobs with confirms. Add lease and attempt fencing, backoff with jitter, a
per-job render process with CPU and memory limits, crop and optimized
variants, the failed registry with audited replay, and staging cleanup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-31 15:36:15 +03:00
co-authored by Claude Opus 5.5
parent 99a222eee2
commit e2a6427c24
102 changed files with 9499 additions and 1916 deletions
+158 -31
View File
@@ -16,7 +16,7 @@ change `async-attachments`, решения 1–3) `pending` становится
"""
from collections.abc import Collection
from datetime import datetime, timedelta
from datetime import datetime
from uuid import UUID
from sqlalchemy import (
@@ -79,6 +79,37 @@ def _later_of_now(now: datetime) -> ColumnElement[datetime]:
return func.greatest(now, Attachment.updated_at)
# очистка staging (design change pipeline-reliability, решение 9)
_STAGING_COLUMNS = (
Attachment.id,
Attachment.object_key,
Attachment.created_at,
Attachment.staging_key,
Attachment.status,
Attachment.updated_at,
)
def _staging_condition(
status: AttachmentStatus,
updated_before: datetime | None,
) -> tuple[ColumnElement[bool], ...]:
# статус — константа: первая колонка индекса, план без параметра
condition = (
Attachment.staging_key.is_not(None),
Attachment.status == literal(status.value, literal_execute=True),
)
if updated_before is None:
return condition
return (*condition, Attachment.updated_at < updated_before)
def _to_staging_candidate(row: Row) -> dataclasses.AttachmentInListDTO:
fields = dict(row._mapping)
fields["status"] = AttachmentStatus(fields["status"])
return dataclasses.AttachmentInListDTO(**fields)
async def insert_attachment(
db_session: AsyncSession,
*,
@@ -136,36 +167,6 @@ async def mark_queued(
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,
*,
@@ -216,6 +217,132 @@ async def return_to_queued(
return (await db_session.execute(statement)).one_or_none() is not None
async def return_group_to_queued(
db_session: AsyncSession,
*,
attachment_ids: Collection[UUID],
updated_at: datetime,
) -> int:
"""Истёкшие аренды пакета: `processing` → `queued`; вызывает relay в той
же транзакции, что и возврат заданий."""
statement = (
update(Attachment)
.where(
Attachment.id == any_(_array(list(attachment_ids), Uuid())),
Attachment.status == AttachmentStatus.PROCESSING.value,
)
.values(
status=AttachmentStatus.QUEUED.value,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return len((await db_session.execute(statement)).all())
async def replay_failed(
db_session: AsyncSession,
*,
attachment_id: UUID,
updated_at: datetime,
) -> bool:
"""Replay: `failed` → `queued`, `error_code` NULL. `False` — условие уже
не выполняется."""
statement = (
update(Attachment)
.where(
Attachment.id == attachment_id,
Attachment.status == AttachmentStatus.FAILED.value,
)
.values(
status=AttachmentStatus.QUEUED.value,
error_code=None,
updated_at=_later_of_now(updated_at),
)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def lock_attachment(
db_session: AsyncSession,
*,
attachment_id: UUID,
) -> dataclasses.AttachmentFullDTO | None:
"""Строка под `FOR NO KEY UPDATE`: отправка сообщения со ссылкой на
вложение берёт `FOR KEY SHARE` и не ждёт (design change
`pipeline-reliability`, решение 9)."""
statement = (
select(*_ATTACHMENT_COLUMNS)
.where(Attachment.id == attachment_id)
.with_for_update(key_share=True)
)
row = (await db_session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def get_staging_candidates(
db_session: AsyncSession,
*,
status: AttachmentStatus,
updated_before: datetime | None,
after: tuple[datetime, UUID] | None,
limit: int,
) -> list[dataclasses.AttachmentInListDTO]:
"""Вложения этого статуса с объектом staging, keyset по `(updated_at, id)`
индекса `ix_attachments_staging_cleanup`, без блокировки."""
statement = (
select(*_STAGING_COLUMNS)
.where(*_staging_condition(status, updated_before))
.order_by(Attachment.updated_at, Attachment.id)
.limit(limit)
)
if after is not None:
statement = statement.where(
tuple_(Attachment.updated_at, Attachment.id) > tuple_(*after),
)
rows = (await db_session.execute(statement)).all()
return [_to_staging_candidate(row) for row in rows]
async def lock_staging_candidate(
db_session: AsyncSession,
*,
attachment_id: UUID,
status: AttachmentStatus,
updated_before: datetime | None,
) -> dataclasses.AttachmentInListDTO | None:
"""Та же строка с теми же условиями под `FOR NO KEY UPDATE SKIP LOCKED`
до конца транзакции; вызов S3 под ней не держит отправку сообщения со
ссылкой на вложение. `None` — условия уже нет или строку держат."""
statement = (
select(*_STAGING_COLUMNS)
.where(
Attachment.id == attachment_id,
*_staging_condition(status, updated_before),
)
.with_for_update(key_share=True, skip_locked=True)
)
row = (await db_session.execute(statement)).one_or_none()
return None if row is None else _to_staging_candidate(row)
async def clear_staging_key(
db_session: AsyncSession,
*,
attachment_id: UUID,
) -> bool:
"""Объект staging убран; `updated_at` не меняется: метаданные готового
вложения те же."""
statement = (
update(Attachment)
.where(Attachment.id == attachment_id)
.values(staging_key=None)
.returning(Attachment.id)
)
return (await db_session.execute(statement)).one_or_none() is not None
async def commit_ready(
db_session: AsyncSession,
*,