from __future__ import annotations import json import logging from typing import Any import aio_pika from aio_pika import DeliveryMode, ExchangeType from app.config import BROKER_URL logger = logging.getLogger("messenger.broker") EXCHANGE_NAME = "messenger.attachments" QUEUE_NAME = "messenger.attachments.jobs" ROUTING_KEY = "attachment.process" DLX_NAME = "messenger.attachments.dlx" DLQ_NAME = "messenger.attachments.dlq" DL_ROUTING_KEY = "attachment.dead" async def setup_broker_topology(channel: aio_pika.abc.AbstractChannel) -> tuple[aio_pika.abc.AbstractExchange, aio_pika.abc.AbstractQueue]: """Настраивает durable exchange, durable очереди и связку с Dead Letter Exchange.""" # 1. Dead Letter Exchange и Dead Letter Queue dlx = await channel.declare_exchange( DLX_NAME, type=ExchangeType.DIRECT, durable=True, ) dlq = await channel.declare_queue( DLQ_NAME, durable=True, ) await dlq.bind(dlx, routing_key=DL_ROUTING_KEY) # 2. Основной Exchange и Queue с dead-lettering exchange = await channel.declare_exchange( EXCHANGE_NAME, type=ExchangeType.DIRECT, durable=True, ) queue = await channel.declare_queue( QUEUE_NAME, durable=True, arguments={ "x-dead-letter-exchange": DLX_NAME, "x-dead-letter-routing-key": DL_ROUTING_KEY, }, ) await queue.bind(exchange, routing_key=ROUTING_KEY) return exchange, queue class BrokerPublisher: """Отказоустойчивый издатель сообщений в RabbitMQ с поддержкой Publisher Confirms.""" def __init__(self, broker_url: str = BROKER_URL) -> None: self.broker_url = broker_url self._connection: aio_pika.abc.AbstractRobustConnection | None = None self._channel: aio_pika.abc.AbstractChannel | None = None self._exchange: aio_pika.abc.AbstractExchange | None = None async def get_exchange(self) -> aio_pika.abc.AbstractExchange: if self._exchange is None or self._channel is None or self._channel.is_closed: if self._connection is None or self._connection.is_closed: self._connection = await aio_pika.connect_robust(self.broker_url) self._channel = await self._connection.channel(publisher_confirms=True) self._exchange, _ = await setup_broker_topology(self._channel) return self._exchange async def publish_job(self, job_dict: dict[str, Any]) -> bool: try: exchange = await self.get_exchange() payload = json.dumps(job_dict, ensure_ascii=False).encode("utf-8") message = aio_pika.Message( body=payload, delivery_mode=DeliveryMode.PERSISTENT, content_type="application/json", message_id=str(job_dict.get("job_id", "")), ) await exchange.publish( message, routing_key=ROUTING_KEY, mandatory=True, ) return True except Exception as exc: logger.error("Failed to publish job to broker: %s", exc) self._exchange = None self._channel = None return False async def close(self) -> None: try: if self._channel and not self._channel.is_closed: await self._channel.close() if self._connection and not self._connection.is_closed: await self._connection.close() except Exception: pass self._exchange = None self._channel = None self._connection = None publisher = BrokerPublisher()