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
-2
View File
@@ -2,7 +2,6 @@ from src.infra.broker.client import (
JobConsumer,
JobDelivery,
JobPublisher,
create_job_publisher,
queue_name,
)
@@ -10,6 +9,5 @@ __all__ = [
"JobConsumer",
"JobDelivery",
"JobPublisher",
"create_job_publisher",
"queue_name",
]
+111 -38
View File
@@ -10,10 +10,11 @@ Design change `async-attachments`, решение 5. Соединение отк
скрыл бы, что исход публикации неизвестен. Признаку `is_closed` соединения
верить нельзя: проба показала закрытый канал при «живом» соединении, поэтому
издатель сбрасывает соединение после любой ошибки, а новое откроет следующий
вызов. Закрытый канал перед публикацией — брокер перезапускался, пока загрузок
не было: в него ничего не ушло, и это не повтор, а новое соединение. Иначе
первая загрузка после возврата брокера получила бы 503 (спек `message-broker`,
«Брокер вернулся»). Повторов издатель не делает: загрузку повторяет клиент.
вызов. Закрытый канал перед публикацией — брокер перезапускался, пока заданий
не было: в него ничего не ушло, и это не повтор, а новое соединение. Повторов
издатель не делает: неподтверждённое опубликует следующий проход relay. Издателя
использует только relay, потребитель — только worker; у реплик API клиента брокера
нет (design change `pipeline-reliability`, решение 1).
Адрес и пароль передаются отдельными аргументами, строка URL с паролем не
собирается. В журнал — адрес, очередь, `id`, длительность и класс ошибки;
@@ -22,7 +23,7 @@ Design change `async-attachments`, решение 5. Соединение отк
import asyncio
import time
from collections.abc import AsyncIterator
from collections.abc import AsyncIterator, Sequence
from dataclasses import dataclass
from typing import Any
from uuid import UUID
@@ -77,12 +78,12 @@ async def _declare_queue(
class JobPublisher:
"""Издатель заданий процесса: одно соединение, публикации по очереди
"""Издатель заданий процесса relay: одно соединение, публикации по очереди
подтверждений канала.
`publish` считает сообщение принятым только после подтверждения брокера.
Срок `[broker] publish_timeout_seconds` покрывает соединение, канал,
публикацию и подтверждение. Любая ошибка — `BrokerUnavailable`.
Сообщение принято только после подтверждения брокера. Срок `[broker]
publish_timeout_seconds` покрывает соединение, канал, публикации и
подтверждения пакета (design change `pipeline-reliability`, решение 2).
"""
def __init__(self, broker: BrokerSettings, *, namespace: str) -> None:
@@ -91,42 +92,120 @@ class JobPublisher:
self.queue = queue_name(namespace)
self._connection: AbstractRobustConnection | None = None
self._channel: AbstractChannel | None = None
# открытие одно на процесс: конкурентные загрузки ждут его, а не
# открытие одно на процесс: конкурентные вызовы ждут его, а не
# открывают по соединению
self._opening = asyncio.Lock()
self._down = False
self._close_tasks: set[asyncio.Task[None]] = set()
async def publish(self, body: bytes, *, message_id: UUID) -> None:
async def publish_many(
self,
items: Sequence[tuple[UUID, bytes]],
) -> set[UUID]:
"""Пакет `(id, тело)` с подтверждением под одним сроком. Возвращает
подтверждённые `id`. Подмножество — ошибка уже записана, соединение
сброшено: подтверждённые до срока отмечаются, исход остальных неизвестен,
и их опубликует следующий проход (возможен дубль)."""
started = time.monotonic()
channel: AbstractChannel | None = None
confirmed: set[UUID] = set()
timeout = self._broker.publish_timeout_seconds
deadline = asyncio.get_running_loop().time() + timeout
failure: BaseException | None = None
tasks: dict[asyncio.Task[object], UUID] = {}
try:
async with asyncio.timeout_at(deadline):
channel = await self._get_channel()
tasks = {
asyncio.create_task(
self._publish_one(channel, body, job_id),
): job_id
for job_id, body in items
}
remaining = deadline - asyncio.get_running_loop().time()
done, pending = await asyncio.wait(
tasks,
timeout=max(remaining, 0),
)
for task in pending:
task.cancel()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
failure = TimeoutError()
for task in done:
error = task.exception()
if error is None:
confirmed.add(tasks[task])
else:
failure = error
except Exception as e:
failure = e
if failure is not None:
self._failed(channel, failure, started=started)
return confirmed
self._recovered()
logger.debug(
"Published jobs",
count=len(confirmed),
broker_queue=self.queue,
duration_ms=round((time.monotonic() - started) * 1000),
)
return confirmed
async def _publish_one(
self,
channel: AbstractChannel,
body: bytes,
job_id: UUID,
) -> None:
"""Сообщение persistent в очередь через default exchange, `mandatory`:
без маршрута брокер вернёт его, и это ошибка."""
await channel.default_exchange.publish(
aio_pika.Message(
body,
content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=str(job_id),
),
routing_key=self.queue,
mandatory=True,
)
async def ready_messages(self) -> int:
"""Готовые сообщения очереди: активное объявление, которое создаёт ещё и
удалённую очередь. Неподтверждённые у потребителей в счёт не идут.
Отказ — `BrokerUnavailable`."""
started = time.monotonic()
channel: AbstractChannel | None = None
try:
async with asyncio.timeout(self._broker.publish_timeout_seconds):
channel = await self._get_channel()
await channel.default_exchange.publish(
aio_pika.Message(
body,
content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=str(message_id),
),
routing_key=self.queue,
mandatory=True,
)
queue = await _declare_queue(channel, name=self.queue)
except Exception as e:
self._reset(channel)
self._down = True
logger.warning(
"Broker is unavailable",
broker_host=self._broker.host,
broker_port=self._broker.port,
broker_queue=self.queue,
error_type=type(e).__name__,
duration_ms=round((time.monotonic() - started) * 1000),
)
self._failed(channel, e, started=started)
raise BrokerUnavailable from e
self._recovered()
return queue.declaration_result.message_count
def _failed(
self,
channel: AbstractChannel | None,
error: BaseException,
*,
started: float,
) -> None:
self._reset(channel)
self._down = True
logger.warning(
"Broker is unavailable",
broker_host=self._broker.host,
broker_port=self._broker.port,
broker_queue=self.queue,
error_type=type(error).__name__,
duration_ms=round((time.monotonic() - started) * 1000),
)
def _recovered(self) -> None:
if self._down:
self._down = False
logger.info(
@@ -134,12 +213,6 @@ class JobPublisher:
broker_host=self._broker.host,
broker_port=self._broker.port,
)
logger.debug(
"Published job",
job_id=message_id,
broker_queue=self.queue,
duration_ms=round((time.monotonic() - started) * 1000),
)
async def _get_channel(self) -> AbstractChannel:
if self._channel is not None and self._channel.is_closed:
@@ -151,7 +224,7 @@ class JobPublisher:
return self._channel
connection = await _open_connection(
self._broker,
client_name="messenger-publisher",
client_name="messenger-relay",
)
try:
channel = await connection.channel(
-16
View File
@@ -1,16 +0,0 @@
"""Издатель заданий процесса API.
Создаётся при импорте по `settings.broker`, соединение открывает первая
публикация: без брокера процесс стартует. Импортируют модуль только
`src/main.py` (закрытие в lifespan) и `src/api/dependencies.py`. Очередь — по
имени базы из `settings.database`: `make test_isolated` с базой `test_<db>` не
смешивается с рабочей.
"""
from src.config import settings
from src.infra.broker.client import create_job_publisher
job_publisher = create_job_publisher(
settings.broker,
namespace=settings.database.name,
)
+2
View File
@@ -4,6 +4,7 @@
from src.infra.db.models.attachment import (
Attachment,
AttachmentJob,
AttachmentJobReplay,
AttachmentVariant,
MessageAttachment,
)
@@ -17,6 +18,7 @@ from src.infra.db.models.user import User
__all__ = [
"Attachment",
"AttachmentJob",
"AttachmentJobReplay",
"AttachmentVariant",
"Base",
"Chat",
+74 -3
View File
@@ -91,6 +91,15 @@ class Attachment(Base):
"id",
postgresql_where=text("status = 'pending'"),
),
# кандидаты очистки staging keyset (design change
# pipeline-reliability, решения 9 и 10)
Index(
"ix_attachments_staging_cleanup",
"status",
"updated_at",
"id",
postgresql_where=text("staging_key IS NOT NULL"),
),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
@@ -117,9 +126,10 @@ class Attachment(Base):
class AttachmentJob(Base):
"""Логическая работа над вложением: `job_id` контракта, счёт попыток и
будущий outbox — `state = 'queued' AND published_at IS NULL` (design
change `async-attachments`, решение 1). Одна на вложение и версию; при
повторах и повторной доставке `id` не меняется."""
outbox — `state = 'queued' AND published_at IS NULL` (design change
`async-attachments`, решение 1; `pipeline-reliability`, решения 1 и 10).
Одна на вложение и версию; при повторах, повторной доставке и replay `id`
не меняется."""
__tablename__ = "attachment_jobs"
__table_args__ = (
@@ -130,6 +140,33 @@ class AttachmentJob(Base):
name="state",
),
CheckConstraint("attempt >= 0", name="attempt"),
CheckConstraint(
"attempt_base BETWEEN 0 AND attempt",
name="attempt_base",
),
# Autogenerate условие и выражение не видит; в ревизии — CONCURRENTLY.
# Запросы пишут state константой, иначе общий план подготовленного
# выражения индекс не возьмёт
Index(
"ix_attachment_jobs_outbox",
text("COALESCE(next_attempt_at, created_at)"),
"id",
postgresql_where=text(
"state = 'queued' AND published_at IS NULL",
),
),
Index(
"ix_attachment_jobs_published",
"published_at",
postgresql_where=text(
"state = 'queued' AND published_at IS NOT NULL",
),
),
Index(
"ix_attachment_jobs_lease",
"lease_expires_at",
postgresql_where=text("state = 'processing'"),
),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
@@ -142,6 +179,13 @@ class AttachmentJob(Base):
Integer,
server_default=text("0"),
)
# значение attempt при последнем replay: бюджет — attempt - attempt_base,
# сам attempt монотонен, это fencing-токен (design change
# pipeline-reliability, решение 5)
attempt_base: 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(
@@ -160,6 +204,33 @@ class AttachmentJob(Base):
)
class AttachmentJobReplay(Base):
"""Запись аудита replay задания `failed` (design change
`pipeline-reliability`, решения 5 и 10): кто, когда, прежние код и
причина, число попыток. Без каскада: задание с записью удалить нельзя."""
__tablename__ = "attachment_job_replays"
__table_args__ = (
CheckConstraint(
"char_length(operator) BETWEEN 1 AND 64",
name="operator_length",
),
CheckConstraint("attempt >= 0", name="attempt"),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
job_id: Mapped[UUID] = mapped_column(
ForeignKey("attachment_jobs.id"),
index=True,
)
operator: Mapped[str] = mapped_column(Text)
# прежний error_code вложения
error_code: Mapped[str | None] = mapped_column(Text)
# прежняя причина задания (last_error_code)
reason: Mapped[str | None] = mapped_column(Text)
attempt: Mapped[int] = mapped_column(Integer)
class AttachmentVariant(Base):
"""Вариант готового вложения; первичный ключ — ключ эффекта контракта
`(attachment_id, pipeline_version, variant)`: повтор второй строки не
+3
View File
@@ -0,0 +1,3 @@
from .client import ImageRenderer
__all__ = ["ImageRenderer"]
+146
View File
@@ -0,0 +1,146 @@
"""Клиент процесса обработки изображения: граница worker и декодера.
Design change `pipeline-reliability`, решение 7. На задание — новый процесс
`python -m src.worker.render`: окружение без секретов, вход в stdin, срок по стене
на стороне родителя. `finally` всегда убивает процесс и дожидается его: отмена
попытки при остановке или по сроку процесс не оставит. Коды выхода переводятся в
исключения: постоянные — `ImageRejected`, временные — `RenderInterrupted`, срок —
`TimeoutError`, как у остальных шагов попытки.
"""
import asyncio
import json
import os
import signal
import sys
import time
from contextlib import suppress
from pathlib import Path
from src.config.settings import Worker as WorkerSettings
from src.core.exceptions import ImageRejected, RenderInterrupted
from src.infra.logger import AbstractLogger, get_logger
from src.schemas.dataclasses import RenderedVariantDTO, RenderedVariantsDTO
from src.schemas.enums import AttachmentJobReason, AttachmentVariantName
from src.utils.constants import ATTACHMENT_MAX_PIXELS
logger: AbstractLogger = get_logger().bind(module="image_renderer")
_RENDER_MODULE = "src.worker.render"
# корень приложения: `-m src.worker.render` ищет пакет от рабочего каталога
_APP_ROOT = Path(__file__).resolve().parent.parent.parent.parent
# только это из окружения родителя: секретов у процесса нет
_INHERITED_ENV = ("PATH", "MALLOC_MMAP_THRESHOLD_")
# секунды на ожидание убитого процесса: SIGKILL не перехватить
_REAP_TIMEOUT_SECONDS = 1
_EXIT_REASONS = {
3: AttachmentJobReason.UNDECODABLE,
4: AttachmentJobReason.LIMIT_MEMORY,
5: AttachmentJobReason.LIMIT_PIXELS,
-signal.SIGXCPU: AttachmentJobReason.LIMIT_CPU,
}
def _child_env() -> dict[str, str]:
env = {
name: os.environ[name] for name in _INHERITED_ENV if name in os.environ
}
env["PYTHONDONTWRITEBYTECODE"] = "1"
env["PYTHONUNBUFFERED"] = "1"
return env
class ImageRenderer:
"""Запуск процесса обработки со значениями `[worker]`."""
def __init__(self, worker: WorkerSettings) -> None:
self._timeout = worker.render_timeout_seconds
self._arguments = (
"--max-pixels",
str(ATTACHMENT_MAX_PIXELS),
"--memory-limit-mib",
str(worker.render_memory_limit_mib),
"--cpu-limit-seconds",
str(worker.render_cpu_limit_seconds),
)
async def render(self, data: bytes) -> RenderedVariantsDTO:
"""Варианты из байтов оригинала. Изображение не прошло —
`ImageRejected`, процесс убит или упал — `RenderInterrupted`, срок —
`TimeoutError`."""
started = time.monotonic()
process = await asyncio.create_subprocess_exec(
sys.executable,
"-m",
_RENDER_MODULE,
*self._arguments,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
env=_child_env(),
cwd=_APP_ROOT,
)
try:
async with asyncio.timeout(self._timeout):
stdout, _ = await process.communicate(data)
finally:
await _reap(process)
code = process.returncode
if code == 0:
return _parse(stdout, started=started)
reason = _EXIT_REASONS.get(code or 0)
if reason is not None:
raise ImageRejected(reason=reason)
logger.warning("Render process failed", exit_code=code)
raise RenderInterrupted(
reason=(
AttachmentJobReason.RENDER_KILLED
if code == -signal.SIGKILL
else AttachmentJobReason.RENDER_CRASHED
),
)
async def _reap(process: asyncio.subprocess.Process) -> None:
if process.returncode is not None:
return
with suppress(ProcessLookupError):
process.kill()
with suppress(TimeoutError):
async with asyncio.timeout(_REAP_TIMEOUT_SECONDS):
await process.wait()
def _parse(stdout: bytes, *, started: float) -> RenderedVariantsDTO:
"""Строка JSON и байты подряд. Испорченный вывод — `render_crashed`."""
try:
line, _, body = stdout.partition(b"\n")
head = json.loads(line)
variants = []
offset = 0
for item in head["variants"]:
size = item["size"]
variants.append(
RenderedVariantDTO(
name=AttachmentVariantName(item["name"]),
content_type=item["content_type"],
width=item["width"],
height=item["height"],
data=body[offset : offset + size],
),
)
offset += size
if offset != len(body) or not variants:
raise ValueError("render output size differs")
return RenderedVariantsDTO(
variants=tuple(variants),
peak_kib=head["peak_kib"],
memory_limit_applied=head["memory_limit_applied"],
render_ms=round((time.monotonic() - started) * 1000),
)
except (ValueError, KeyError, TypeError) as e:
logger.warning("Render process output is damaged")
raise RenderInterrupted(
reason=AttachmentJobReason.RENDER_CRASHED,
) from e