forked from mtusi2026/mtusi2026lab7
lab6_files
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import aio_pika
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.propagate import inject
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import transaction
|
||||
|
||||
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"]))
|
||||
|
||||
# Внедряем W3C traceparent в заголовки
|
||||
headers = {}
|
||||
inject(headers)
|
||||
|
||||
message = aio_pika.Message(
|
||||
body=json.dumps(payload).encode(),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
headers=headers
|
||||
)
|
||||
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)
|
||||
Reference in New Issue
Block a user