forked from mtusi2026/mtusi2026lab5
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:
@@ -70,9 +70,14 @@ class Attachment(Base):
|
||||
name="object_key_length",
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'ready')",
|
||||
"status IN ('pending', 'queued', 'processing', 'ready', 'failed')",
|
||||
name="status",
|
||||
),
|
||||
# код ошибки — только у failed, и у failed он обязателен
|
||||
CheckConstraint(
|
||||
"(status = 'failed') = (error_code IS NOT NULL)",
|
||||
name="error_code_failed",
|
||||
),
|
||||
CheckConstraint(
|
||||
"updated_at >= created_at",
|
||||
name="updated_after_created",
|
||||
@@ -103,6 +108,98 @@ class Attachment(Base):
|
||||
# помечено. Индекса нет: сверка просматривает все строки ready, API
|
||||
# читает по id
|
||||
lost_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
# ключ объекта в staging (design change async-attachments, решение 1);
|
||||
# NULL — строка прежней версии, объект которой сразу по `object_key`
|
||||
staging_key: Mapped[str | None] = mapped_column(Text)
|
||||
# код failed в API; NULL во всех остальных состояниях
|
||||
error_code: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
|
||||
class AttachmentJob(Base):
|
||||
"""Логическая работа над вложением: `job_id` контракта, счёт попыток и
|
||||
будущий outbox — `state = 'queued' AND published_at IS NULL` (design
|
||||
change `async-attachments`, решение 1). Одна на вложение и версию; при
|
||||
повторах и повторной доставке `id` не меняется."""
|
||||
|
||||
__tablename__ = "attachment_jobs"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("attachment_id", "pipeline_version"),
|
||||
CheckConstraint("pipeline_version >= 1", name="pipeline_version"),
|
||||
CheckConstraint(
|
||||
"state IN ('queued', 'processing', 'succeeded', 'failed')",
|
||||
name="state",
|
||||
),
|
||||
CheckConstraint("attempt >= 0", name="attempt"),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(primary_key=True)
|
||||
# без каскада: вложение с заданием удалить нельзя
|
||||
attachment_id: Mapped[UUID] = mapped_column(ForeignKey("attachments.id"))
|
||||
pipeline_version: Mapped[int] = mapped_column(Integer)
|
||||
state: Mapped[str] = mapped_column(Text)
|
||||
# начатые попытки; источник истины счёта, а не заголовки брокера
|
||||
attempt: Mapped[int] = mapped_column(
|
||||
Integer,
|
||||
server_default=text("0"),
|
||||
)
|
||||
# причина последней ошибки для оператора, без секретов
|
||||
last_error_code: Mapped[str | None] = mapped_column(Text)
|
||||
next_attempt_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
)
|
||||
lease_expires_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
)
|
||||
# когда брокер подтвердил последнее сообщение; NULL — намерение не передано
|
||||
published_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
||||
finished_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
)
|
||||
|
||||
|
||||
class AttachmentVariant(Base):
|
||||
"""Вариант готового вложения; первичный ключ — ключ эффекта контракта
|
||||
`(attachment_id, pipeline_version, variant)`: повтор второй строки не
|
||||
создаёт. Оригинал — не строка этой таблицы."""
|
||||
|
||||
__tablename__ = "attachment_variants"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"variant IN ('thumbnail', 'crop', 'optimized')",
|
||||
name="variant",
|
||||
),
|
||||
CheckConstraint(
|
||||
f"octet_length(object_key) BETWEEN 1 AND {OBJECT_KEY_MAX_BYTES}",
|
||||
name="object_key_length",
|
||||
),
|
||||
CheckConstraint(
|
||||
"content_type IN ('image/jpeg', 'image/png', 'image/webp')",
|
||||
name="content_type",
|
||||
),
|
||||
CheckConstraint("size_bytes > 0", name="size_bytes"),
|
||||
CheckConstraint("width > 0", name="width"),
|
||||
CheckConstraint("height > 0", name="height"),
|
||||
CheckConstraint(
|
||||
f"octet_length(sha256) = {ATTACHMENT_SHA256_BYTES}",
|
||||
name="sha256_length",
|
||||
),
|
||||
)
|
||||
|
||||
attachment_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey("attachments.id"),
|
||||
primary_key=True,
|
||||
)
|
||||
pipeline_version: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
variant: Mapped[str] = mapped_column(Text, primary_key=True)
|
||||
object_key: Mapped[str] = mapped_column(Text, unique=True)
|
||||
content_type: Mapped[str] = mapped_column(Text)
|
||||
size_bytes: Mapped[int] = mapped_column(Integer)
|
||||
width: Mapped[int] = mapped_column(Integer)
|
||||
height: Mapped[int] = mapped_column(Integer)
|
||||
sha256: Mapped[bytes] = mapped_column(LargeBinary)
|
||||
|
||||
|
||||
class MessageAttachment(Base):
|
||||
|
||||
Reference in New Issue
Block a user