"""Durable RabbitMQ queue. Publish waits for a broker confirm; the worker acks later.""" import logging import aio_pika from aio_pika import DeliveryMode, Message from .jobs import QUEUE, QUEUE_ARGUMENTS logger = logging.getLogger('messenger') class BrokerDown(Exception): """The broker did not confirm. The message stays internal and has no URL.""" class Broker: def __init__(self, url: str) -> None: self._url = url self._connection: aio_pika.abc.AbstractRobustConnection | None = None self.channel: aio_pika.abc.AbstractChannel | None = None async def connect(self) -> None: try: self._connection = await aio_pika.connect_robust(self._url, timeout=10) # Confirms make publish wait until the broker has the message, not only the socket. self.channel = await self._connection.channel(publisher_confirms=True, on_return_raises=True) await self.channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS) except Exception: raise RuntimeError('broker did not become reachable') from None async def close(self) -> None: if self._connection is not None: await self._connection.close() async def ready(self) -> None: connection = self._connection if connection is None or connection.is_closed or connection.reconnecting: raise BrokerDown() async def publish(self, body: bytes) -> None: """Persistent message. Returns after the broker confirms it, or raises BrokerDown.""" if self.channel is None: raise BrokerDown() message = Message( body, content_type='application/json', delivery_mode=DeliveryMode.PERSISTENT, ) try: await self.channel.default_exchange.publish( message, routing_key=QUEUE, mandatory=True, timeout=10, ) except Exception as exc: logger.warning('broker did not confirm a job (%s)', type(exc).__name__) raise BrokerDown() from None