This commit is contained in:
caramelteawithmint
2026-11-27 07:52:15 +03:00
parent 6b60dd5d74
commit d8b193f62b
20 changed files with 966 additions and 150 deletions
+29 -20
View File
@@ -2,51 +2,60 @@ import asyncio
import json
import logging
import aio_pika
from src.app.config import get_settings
from src.app.db import transaction
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"
"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"],))
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) # Если пусто, ждем секунду
await asyncio.sleep(1)
except Exception as e:
logger.error(f"Outbox error: {e}")
logger.error("Outbox error: %s", e)
await asyncio.sleep(2)