Files
mtusi2026lab5/app/broker.py
T

69 lines
2.6 KiB
Python

import asyncio
import json
import os
import aio_pika
from aio_pika.abc import AbstractRobustConnection
from app.config import config
_connection: AbstractRobustConnection | None = None
_lock = asyncio.Lock()
PREFETCH_COUNT = int(os.getenv("PREFETCH_COUNT", "1"))
async def get_connection() -> AbstractRobustConnection:
global _connection
async with _lock:
if _connection is None or _connection.is_closed:
_connection = await aio_pika.connect_robust(config.RABBITMQ_URL)
return _connection
async def publish_job(job: dict, is_dlq: bool = False) -> None:
connection = await get_connection()
channel = await connection.channel()
queue_name = config.RABBITMQ_QUEUE + (".dlq" if is_dlq else "")
await channel.declare_queue(queue_name, durable=True)
await channel.default_exchange.publish(
aio_pika.Message(
body=json.dumps(job).encode(),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
content_type="application/json",
),
routing_key=queue_name,
)
await channel.close()
async def consume_jobs(handler) -> None:
while True:
try:
connection = await get_connection()
channel = await connection.channel()
await channel.set_qos(prefetch_count=PREFETCH_COUNT)
queue = await channel.declare_queue(config.RABBITMQ_QUEUE, durable=True)
# Запускаем обработчик в фоне, чтобы не блокировать цикл
async def process_message(message: aio_pika.IncomingMessage):
try:
job = json.loads(message.body)
print(f"[broker] got job: {job.get('attachment_id')}", flush=True)
await handler(job)
await message.ack()
except Exception as e:
print(f"[broker] handler error: {e}", flush=True)
await message.reject(requeue=False)
async def on_message(message: aio_pika.IncomingMessage):
# Запускаем в фоне, не ждем завершения, чтобы сразу взять следующее
asyncio.create_task(process_message(message))
await queue.consume(on_message)
print(f"[broker] listening for jobs (prefetch={PREFETCH_COUNT})...", flush=True)
await asyncio.Future()
except Exception as e:
print(f"[broker] connection error: {e}. Reconnecting in 3 seconds...", flush=True)
await asyncio.sleep(3)