forked from mtusi2026/mtusi2026lab5
level 4
This commit is contained in:
+38
-20
@@ -1,10 +1,11 @@
|
||||
"""Durable RabbitMQ queue. Publish waits for a broker confirm; the worker acks later."""
|
||||
"""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 QUEUE, QUEUE_ARGUMENTS
|
||||
from .jobs import DLQ, DLQ_ARGUMENTS, QUEUE, QUEUE_ARGUMENTS
|
||||
|
||||
logger = logging.getLogger('messenger')
|
||||
|
||||
@@ -18,13 +19,19 @@ class Broker:
|
||||
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.channel.declare_queue(QUEUE, durable=True, arguments=QUEUE_ARGUMENTS)
|
||||
await self._declare(self.channel)
|
||||
except Exception:
|
||||
raise RuntimeError('broker did not become reachable') from None
|
||||
|
||||
@@ -37,22 +44,33 @@ class Broker:
|
||||
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:
|
||||
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()
|
||||
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,
|
||||
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,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning('broker did not confirm a job (%s)', type(exc).__name__)
|
||||
raise BrokerDown() from None
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user