137 lines
5.0 KiB
Python
137 lines
5.0 KiB
Python
import os
|
||
import json
|
||
import random
|
||
import logging
|
||
import asyncio
|
||
from datetime import datetime, timezone
|
||
from sqlalchemy import select
|
||
from sqlalchemy.ext.asyncio import AsyncSession
|
||
import aio_pika
|
||
from app.models import JobOutbox
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
BROKER_URL = os.getenv("BROKER_URL", "amqp://messenger:mq_secret_password@rabbitmq:5672/")
|
||
|
||
MAIN_QUEUE = "attachment.process.v1"
|
||
DLX_NAME = "attachments.dlx"
|
||
DLQ_NAME = "attachment.process.dlq"
|
||
RETRY_EXCHANGE = "attachments.retry"
|
||
|
||
# Лестница отложенных очередей: фиксированный TTL на очередь,
|
||
# поэтому нет head-of-line blocking (в отличие от per-message TTL).
|
||
RETRY_TIERS = [1, 2, 4, 8, 16, 32, 60]
|
||
BASE_DELAY = 1
|
||
MAX_DELAY = 60
|
||
|
||
_connection = None
|
||
_channel = None
|
||
|
||
|
||
def retry_queue_name(tier: int) -> str:
|
||
return f"attachment.process.retry.{tier}s"
|
||
|
||
|
||
def choose_retry_tier(attempt: int) -> int:
|
||
"""Экспоненциальный backoff с equal jitter, квантованный по лестнице TTL."""
|
||
exp = min(BASE_DELAY * (2 ** (attempt - 1)), MAX_DELAY)
|
||
delay = random.uniform(exp / 2, exp) # equal jitter
|
||
for tier in RETRY_TIERS:
|
||
if tier >= delay:
|
||
return tier
|
||
return RETRY_TIERS[-1]
|
||
|
||
|
||
async def declare_topology(channel: aio_pika.Channel):
|
||
"""Идемпотентное объявление обменов и очередей. Аргументы неизменяемы!"""
|
||
dlx = await channel.declare_exchange(DLX_NAME, aio_pika.ExchangeType.DIRECT, durable=True)
|
||
dlq = await channel.declare_queue(DLQ_NAME, durable=True)
|
||
await dlq.bind(dlx, routing_key=DLQ_NAME)
|
||
|
||
retry_ex = await channel.declare_exchange(RETRY_EXCHANGE, aio_pika.ExchangeType.DIRECT, durable=True)
|
||
for tier in RETRY_TIERS:
|
||
name = retry_queue_name(tier)
|
||
q = await channel.declare_queue(
|
||
name,
|
||
durable=True,
|
||
arguments={
|
||
"x-message-ttl": tier * 1000,
|
||
"x-dead-letter-exchange": "", # default exchange
|
||
"x-dead-letter-routing-key": MAIN_QUEUE, # после TTL -> в основную очередь
|
||
},
|
||
)
|
||
await q.bind(retry_ex, routing_key=name)
|
||
|
||
await channel.declare_queue(
|
||
MAIN_QUEUE,
|
||
durable=True,
|
||
arguments={
|
||
"x-dead-letter-exchange": DLX_NAME,
|
||
"x-dead-letter-routing-key": DLQ_NAME,
|
||
},
|
||
)
|
||
logger.info("RabbitMQ topology ready: main=%s, retry tiers=%s, dlq=%s", MAIN_QUEUE, RETRY_TIERS, DLQ_NAME)
|
||
|
||
|
||
async def get_channel() -> aio_pika.Channel:
|
||
"""Канал с publisher confirms (aio-pika по умолчанию publisher_confirms=True)."""
|
||
global _connection, _channel
|
||
if _connection is None or _connection.is_closed or _channel is None or _channel.is_closed:
|
||
_connection = await aio_pika.connect_robust(BROKER_URL)
|
||
_channel = await _connection.channel() # publisher_confirms=True
|
||
await declare_topology(_channel)
|
||
return _channel
|
||
|
||
|
||
async def publish_retry(payload: dict, tier: int):
|
||
"""Отложенная повторная доставка: сообщение полежит tier секунд и вернётся в main."""
|
||
channel = await get_channel()
|
||
retry_ex = await channel.get_exchange(RETRY_EXCHANGE)
|
||
await retry_ex.publish(
|
||
aio_pika.Message(
|
||
body=json.dumps(payload).encode(),
|
||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||
),
|
||
routing_key=retry_queue_name(tier),
|
||
)
|
||
logger.info("Scheduled retry in %ss for job %s (attempt %s)", tier, payload.get("job_id"), payload.get("attempt"))
|
||
|
||
|
||
async def publish_main(payload: dict):
|
||
channel = await get_channel()
|
||
await channel.default_exchange.publish(
|
||
aio_pika.Message(
|
||
body=json.dumps(payload).encode(),
|
||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||
),
|
||
routing_key=MAIN_QUEUE,
|
||
)
|
||
|
||
|
||
async def relay_outbox(db: AsyncSession):
|
||
"""Transactional outbox: publish + confirm, только потом published_at."""
|
||
stmt = select(JobOutbox).where(JobOutbox.published_at.is_(None)).limit(10)
|
||
result = await db.execute(stmt)
|
||
for record in result.scalars().all():
|
||
try:
|
||
await publish_main(record.payload) # ждём publisher confirm
|
||
record.published_at = datetime.now(timezone.utc)
|
||
await db.commit()
|
||
logger.info("Relayed job %s to broker", record.job_id)
|
||
except Exception as e:
|
||
logger.error("Failed to relay job %s: %s", record.job_id, e)
|
||
await db.rollback()
|
||
|
||
|
||
async def run_relay():
|
||
from app.database import AsyncSessionLocal
|
||
while True:
|
||
try:
|
||
async with AsyncSessionLocal() as db:
|
||
await relay_outbox(db)
|
||
await asyncio.sleep(1)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception as e:
|
||
logger.error("Relay loop error: %s", e)
|
||
await asyncio.sleep(5) |