included rabbitmq as broker
This commit is contained in:
+71
-20
@@ -1,27 +1,78 @@
|
||||
"""Заготовки адаптера durable broker; конкретный брокер ещё не выбран.
|
||||
"""RabbitMQ: durable queue, persistent messages, publisher confirms и manual ack."""
|
||||
|
||||
Сообщения соответствуют contracts/jobs.schema.json, содержат ID и служебные
|
||||
поля, но не bytes/credentials/произвольные URL. Подключение, consumer identity,
|
||||
формат delivery handle и интерфейсы уточнить после выбора брокера/версии.
|
||||
Здесь появятся только SDK-вызовы; решения о retry/ready находятся в domain/.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
|
||||
from collections.abc import Mapping
|
||||
import aio_pika
|
||||
from aio_pika.abc import AbstractIncomingMessage
|
||||
|
||||
from app.core.jobs import JobSettings
|
||||
from app.schemas.job import JobMessage
|
||||
|
||||
|
||||
async def publish_job(payload: Mapping[str, object]) -> str:
|
||||
"""Опубликовать устойчивое сообщение и вернуть идентификатор доставки.
|
||||
|
||||
Дождаться подтверждения сохранения брокером; неопределённый исход разрешает
|
||||
повтор с тем же job_id. Не считать публикацию обработкой изображения.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: публикация в брокер ещё не реализована")
|
||||
@dataclass(frozen=True)
|
||||
class Delivery:
|
||||
id: AbstractIncomingMessage
|
||||
payload: bytes
|
||||
|
||||
|
||||
async def acknowledge_job(delivery_id: str) -> None:
|
||||
"""Подтвердить доставку после устойчивого эффекта либо проверенного ready-дубля.
|
||||
class JobBroker:
|
||||
"""Один consumer/канал на экземпляр; publisher использует отдельный экземпляр."""
|
||||
|
||||
Retry сначала устойчиво планируется, затем закрывается старая доставка.
|
||||
Конкретный delivery handle зависит от брокера; сигнатура предварительная.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: ack ещё не реализован")
|
||||
def __init__(self, settings: JobSettings) -> None:
|
||||
self.settings = settings
|
||||
self.connection = self.channel = self.queue = self.iterator = None
|
||||
# Transport exceptions могут содержать URL с credentials.
|
||||
logging.getLogger("aio_pika").setLevel(logging.CRITICAL)
|
||||
logging.getLogger("aiormq").setLevel(logging.CRITICAL)
|
||||
|
||||
async def ensure_ready(self) -> None:
|
||||
if self.connection is None or self.connection.is_closed or self.channel is None or self.channel.is_closed:
|
||||
await self.aclose()
|
||||
self.connection = await aio_pika.connect(
|
||||
host=self.settings.broker_host, port=self.settings.broker_port,
|
||||
login=self.settings.broker_user,
|
||||
password=self.settings.broker_password_file.read_text().strip(),
|
||||
virtualhost=self.settings.broker_vhost, timeout=5, heartbeat=30,
|
||||
)
|
||||
self.channel = await self.connection.channel(publisher_confirms=True, on_return_raises=True)
|
||||
await self.channel.set_qos(prefetch_count=1)
|
||||
self.queue = await self.channel.declare_queue(self.settings.broker_queue, durable=True)
|
||||
|
||||
async def publish_job(self, message: JobMessage) -> None:
|
||||
await self.ensure_ready()
|
||||
await self.channel.default_exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=message.model_dump_json(exclude_none=True).encode(),
|
||||
content_type="application/json", delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=f"{message.job_id}:{message.attempt}",
|
||||
), routing_key=self.settings.broker_queue, mandatory=True, timeout=10,
|
||||
)
|
||||
|
||||
async def receive(self, consumer: str) -> Delivery:
|
||||
await self.ensure_ready()
|
||||
if self.iterator is None:
|
||||
self.iterator = self.queue.iterator(no_ack=False, consumer_tag=consumer)
|
||||
await self.iterator.__aenter__()
|
||||
message = await self.iterator.__anext__()
|
||||
return Delivery(message, message.body)
|
||||
|
||||
async def acknowledge_job(self, delivery_id: AbstractIncomingMessage) -> None:
|
||||
await delivery_id.ack()
|
||||
|
||||
async def defer_job(self, delivery_id: AbstractIncomingMessage) -> None:
|
||||
# Живая чужая lease: не удерживать единственный prefetch slot навсегда.
|
||||
await asyncio.sleep(self.settings.publisher_poll_seconds)
|
||||
await delivery_id.nack(requeue=True)
|
||||
|
||||
async def reject_invalid(self, delivery_id: AbstractIncomingMessage) -> None:
|
||||
# Failed jobs находятся в PostgreSQL; неизвестные payload не копируются в DLQ.
|
||||
logging.getLogger(__name__).warning("Rejected invalid job envelope")
|
||||
await delivery_id.reject(requeue=False)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
connection = self.connection
|
||||
self.connection = self.channel = self.queue = self.iterator = None
|
||||
if connection is not None and not connection.is_closed:
|
||||
await connection.close()
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Операторские выборки и журнал replay; транзакция принадлежит domain."""
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
from app.models.job_replay import JobReplay
|
||||
|
||||
|
||||
async def failed_jobs(session, limit: int):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(Attachment.status == "failed")
|
||||
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id).limit(limit)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
|
||||
async def replay_record(session, request_id):
|
||||
return await session.get(JobReplay, request_id)
|
||||
|
||||
|
||||
async def insert_replay(session, **values) -> bool:
|
||||
result = await session.scalar(insert(JobReplay).values(**values).on_conflict_do_nothing(index_elements=[JobReplay.id]).returning(JobReplay.id))
|
||||
return result is not None
|
||||
|
||||
|
||||
async def replay_history(session, job_id):
|
||||
return (await session.scalars(select(JobReplay).where(JobReplay.job_id == job_id).order_by(JobReplay.created_at).limit(100))).all()
|
||||
|
||||
|
||||
def reset_failed(job, attachment, now, attempt_limit):
|
||||
job.cycle_start_attempt = job.attempt
|
||||
job.attempt_limit = attempt_limit
|
||||
job.published_attempt = job.attempt
|
||||
job.next_attempt_at = now
|
||||
job.lease_token = None
|
||||
job.lease_until = None
|
||||
job.finished_at = None
|
||||
job.last_error_code = None
|
||||
job.last_error_permanent = None
|
||||
attachment.status = "queued"
|
||||
attachment.error_code = None
|
||||
attachment.updated_at = now
|
||||
+116
-26
@@ -1,37 +1,127 @@
|
||||
"""Заготовки PostgreSQL-хранилища jobs lab5; скрытых commit здесь нет.
|
||||
|
||||
Будущие ORM-операции захвата, lease, retry и результата должны защищаться
|
||||
от конкурирующих попыток. Границы транзакций находятся в domain/.
|
||||
Тип результата захвата уточняется после определения модели job.
|
||||
"""
|
||||
"""SQL и изменения jobs/attachments; commit остаётся в domain."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import and_, or_, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def claim_job(session: AsyncSession, job_id: UUID) -> None:
|
||||
"""Условно захватить допустимое задание и сохранить lease/номер попытки.
|
||||
|
||||
Ready и актуальная чужая аренда не переходят обратно в processing.
|
||||
Будущий результат должен различать захват, завершённый дубль и занятость.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: захват job ещё не реализован")
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
from app.schemas.attachment import VARIANT_FILENAMES
|
||||
|
||||
|
||||
async def complete_job(session: AsyncSession, job_id: UUID) -> None:
|
||||
"""Атомарно записать metadata вариантов и ready после сохранения объектов.
|
||||
@dataclass(frozen=True)
|
||||
class JobWork:
|
||||
job_id: UUID
|
||||
attachment_id: UUID
|
||||
lease_token: UUID
|
||||
pipeline_version: int
|
||||
staging_key: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
|
||||
Предусловия lease/attempt/pipeline_version и структура результата будут
|
||||
добавлены в сигнатуру вместе с ORM-моделью. Не делать commit в storage.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: фиксация результата ещё не реализована")
|
||||
@property
|
||||
def original_key(self) -> str:
|
||||
return f"originals/{self.attachment_id.hex}/v{self.pipeline_version}"
|
||||
|
||||
def variant_key(self, name: str) -> str:
|
||||
filename = VARIANT_FILENAMES[name]
|
||||
return f"variants/{self.attachment_id.hex}/v{self.pipeline_version}/{filename}"
|
||||
|
||||
|
||||
async def record_job_failure(session: AsyncSession, job_id: UUID, error_code: str) -> None:
|
||||
"""Записать безопасный код сбоя без stack trace и secrets.
|
||||
async def create_job(session: AsyncSession, attachment_id: UUID, staging_key: str) -> UUID:
|
||||
job = AttachmentJob(attachment_id=attachment_id, staging_key=staging_key)
|
||||
session.add(job)
|
||||
await session.flush()
|
||||
return job.id
|
||||
|
||||
Domain выбирает queued с next_attempt_at либо конечный failed согласно
|
||||
классификации ошибки и лимиту попыток; storage лишь сохраняет решение.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: сохранение сбоя ещё не реализовано")
|
||||
|
||||
async def lock_job(session: AsyncSession, job_id: UUID):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(AttachmentJob.id == job_id)
|
||||
.with_for_update(of=AttachmentJob)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
return result.one_or_none()
|
||||
|
||||
|
||||
async def database_time(session: AsyncSession) -> datetime:
|
||||
return await session.scalar(select(func.clock_timestamp()))
|
||||
|
||||
|
||||
async def expired_jobs(session: AsyncSession, limit: int = 20):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(Attachment.status == "processing", AttachmentJob.lease_until < func.clock_timestamp())
|
||||
.order_by(AttachmentJob.lease_until)
|
||||
.limit(limit)
|
||||
.with_for_update(of=AttachmentJob, skip_locked=True)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
|
||||
def start_job(job, attachment, token: UUID, now: datetime, lease_seconds: int) -> JobWork:
|
||||
job.attempt += 1
|
||||
job.lease_token = token
|
||||
job.lease_until = now + timedelta(seconds=lease_seconds)
|
||||
attachment.status = "processing"
|
||||
attachment.updated_at = now
|
||||
return JobWork(
|
||||
job.id, attachment.id, token, job.pipeline_version, job.staging_key,
|
||||
attachment.content_type, attachment.size_bytes, attachment.sha256,
|
||||
)
|
||||
|
||||
|
||||
def record_failure(job, attachment, now: datetime, error_code: str, *, terminal: bool, retry_seconds: float) -> None:
|
||||
job.lease_token = None
|
||||
job.lease_until = None
|
||||
job.last_error_code = error_code
|
||||
job.next_attempt_at = now + timedelta(seconds=retry_seconds)
|
||||
job.finished_at = now if terminal else None
|
||||
attachment.status = "failed" if terminal else "queued"
|
||||
attachment.error_code = error_code if terminal else None
|
||||
attachment.updated_at = now
|
||||
|
||||
|
||||
def complete_job(job, attachment, work: JobWork, variants: list[dict], now: datetime) -> None:
|
||||
attachment.object_key = work.original_key
|
||||
attachment.thumbnail_key = work.variant_key("thumbnail")
|
||||
attachment.crop_key = work.variant_key("crop")
|
||||
attachment.optimized_key = work.variant_key("optimized")
|
||||
attachment.variants = variants
|
||||
attachment.status = "ready"
|
||||
attachment.error_code = None
|
||||
attachment.updated_at = now
|
||||
job.lease_token = None
|
||||
job.lease_until = None
|
||||
job.last_error_code = None
|
||||
job.last_error_permanent = None
|
||||
job.finished_at = now
|
||||
|
||||
|
||||
async def terminal_staging(session: AsyncSession, retention: int, failed_retention: int, limit: int = 20):
|
||||
result = await session.execute(
|
||||
select(AttachmentJob, Attachment)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(
|
||||
AttachmentJob.staging_key.is_not(None),
|
||||
or_(
|
||||
and_(Attachment.status == "ready", AttachmentJob.finished_at < func.clock_timestamp() - timedelta(seconds=retention)),
|
||||
and_(Attachment.status == "failed", AttachmentJob.finished_at < func.clock_timestamp() - timedelta(seconds=failed_retention)),
|
||||
),
|
||||
)
|
||||
.order_by(AttachmentJob.finished_at)
|
||||
.limit(limit)
|
||||
.with_for_update(of=AttachmentJob, skip_locked=True)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
|
||||
def clear_staging(job) -> None:
|
||||
job.staging_key = None
|
||||
|
||||
+23
-15
@@ -1,23 +1,31 @@
|
||||
"""Заготовки transactional outbox для разрыва PostgreSQL COMMIT → broker.
|
||||
|
||||
Outbox — таблица намерений публикации в той же транзакции, что и job.
|
||||
Повторная публикация после неопределённого confirm допустима; job_id стабилен.
|
||||
Форма записей, захват пачки и lease publisher уточняются вместе с моделью.
|
||||
"""
|
||||
"""Jobs одновременно хранят намерение публикации очередной попытки."""
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def add_job_event(session: AsyncSession, job_id: UUID) -> None:
|
||||
"""Сохранить намерение публикации job без commit и обращения к брокеру."""
|
||||
raise NotImplementedError("Lab5: запись outbox ещё не реализована")
|
||||
from app.models.attachment import Attachment
|
||||
from app.models.job import AttachmentJob
|
||||
|
||||
|
||||
async def mark_event_published(session: AsyncSession, event_id: UUID) -> None:
|
||||
"""Отметить событие опубликованным после устойчивого подтверждения брокера.
|
||||
async def next_unpublished_job(session: AsyncSession, *, attachment_id: UUID | None = None) -> AttachmentJob | None:
|
||||
statement = (
|
||||
select(AttachmentJob)
|
||||
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||
.where(
|
||||
Attachment.status == "queued",
|
||||
AttachmentJob.next_attempt_at <= func.clock_timestamp(),
|
||||
AttachmentJob.published_attempt <= AttachmentJob.attempt,
|
||||
)
|
||||
.order_by(AttachmentJob.next_attempt_at, AttachmentJob.id)
|
||||
.limit(1)
|
||||
.with_for_update(of=AttachmentJob, skip_locked=True)
|
||||
)
|
||||
if attachment_id is not None:
|
||||
statement = statement.where(AttachmentJob.attachment_id == attachment_id)
|
||||
return await session.scalar(statement)
|
||||
|
||||
Не помечать job завершённой: publisher confirm отличается от consumer ack.
|
||||
"""
|
||||
raise NotImplementedError("Lab5: отметка outbox ещё не реализована")
|
||||
|
||||
def mark_published(job: AttachmentJob) -> None:
|
||||
job.published_attempt = job.attempt + 1
|
||||
|
||||
Reference in New Issue
Block a user