Files
mtusi2026lab5-fork/app/broker.py
T
2026-11-22 17:59:11 +03:00

77 lines
3.0 KiB
Python

"""Durable RabbitMQ queues. Publish waits for a broker confirm; the worker acks later."""
import asyncio
import logging
import aio_pika
from aio_pika import DeliveryMode, Message
from .jobs import DLQ, DLQ_ARGUMENTS, 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
self._publish_lock = asyncio.Lock()
async def _declare(self, channel: aio_pika.abc.AbstractChannel) -> aio_pika.abc.AbstractQueue:
await channel.declare_queue(DLQ, durable=True, arguments=DLQ_ARGUMENTS)
return await channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS)
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.
# Consume uses a second channel so acks and confirms do not share one multiplexer.
self.channel = await self._connection.channel(publisher_confirms=True, on_return_raises=True)
await self._declare(self.channel)
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 open_consumer(self, prefetch: int):
"""A channel that only consumes. prefetch caps how many jobs sit unacked."""
if self._connection is None:
raise BrokerDown()
channel = await self._connection.channel()
await channel.set_qos(prefetch_count=prefetch)
queue = await self._declare(channel)
return channel, queue
async def publish(self, body: bytes, queue: str = QUEUE, headers: dict | None = None) -> None:
"""Persistent message. Returns after the broker confirms it, or raises BrokerDown."""
async with self._publish_lock:
if self.channel is None:
raise BrokerDown()
message = Message(
body,
content_type='application/json',
delivery_mode=DeliveryMode.PERSISTENT,
headers=headers,
)
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