52 lines
2.1 KiB
Python
52 lines
2.1 KiB
Python
import asyncio
|
|
import json
|
|
import logging
|
|
import aio_pika
|
|
from src.app.config import get_settings
|
|
from src.app.db import transaction
|
|
from psycopg.rows import dict_row
|
|
|
|
logger = logging.getLogger("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"]
|
|
# Отправляем в RabbitMQ
|
|
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(f"Outbox error: {e}")
|
|
await asyncio.sleep(2) |