import asyncio import json import logging import aio_pika from opentelemetry import trace from psycopg.rows import dict_row from src.app.config import get_settings from src.app.db import transaction from src.app.otel import setup_otel from src.app.logging_config import setup_logging logger = logging.getLogger("outbox") tracer = trace.get_tracer("messenger-outbox") async def publish_loop(): settings = get_settings() while True: try: connection = await aio_pika.connect_robust(settings.broker_url) break except Exception: await asyncio.sleep(5) async with connection: channel = await connection.channel() await channel.declare_queue(settings.broker_queue, durable=True) while True: try: with transaction() as conn: with conn.cursor(row_factory=dict_row) as cur: cur.execute( "SELECT id, payload FROM outbox_messages " "WHERE processed_at IS NULL ORDER BY created_at LIMIT 10 FOR UPDATE SKIP LOCKED" ) messages = cur.fetchall() for msg in messages: payload = msg["payload"] with tracer.start_as_current_span("outbox.publish") as span: span.set_attribute("outbox.message_id", str(msg["id"])) message = aio_pika.Message( body=json.dumps(payload).encode(), delivery_mode=aio_pika.DeliveryMode.PERSISTENT, ) await channel.default_exchange.publish( message, routing_key=settings.broker_queue ) cur.execute( "UPDATE outbox_messages SET processed_at = now() WHERE id = %s", (msg["id"],), ) if not messages: await asyncio.sleep(1) except Exception as e: logger.error("Outbox error: %s", e) await asyncio.sleep(2)