import json import aio_pika from typing import Any from app.config import settings async def get_connection(): return await aio_pika.connect_robust(settings.RABBITMQ_URL) async def publish_task_message(routing_key: str, message: dict[str, Any]): connection = await get_connection() async with connection: channel = await connection.channel() exchange = await channel.declare_exchange( settings.RABBITMQ_EXCHANGE, aio_pika.ExchangeType.TOPIC, durable=True, ) body = json.dumps(message).encode("utf-8") await exchange.publish( aio_pika.Message( body=body, content_type="application/json", delivery_mode=aio_pika.DeliveryMode.PERSISTENT, correlation_id=str(message.get("task_id")), ), routing_key=routing_key, )