Files
mtusi2026lab5/app/outbox_dispatcher.py

138 lines
4.0 KiB
Python

import asyncio
import json
import os
from datetime import datetime, timezone
import aio_pika
from sqlalchemy import select
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.config import DATABASE_URL
from app.models.attachment import Attachment
from app.models.chat import Chat, ChatMember
from app.models.outbox import OutboxEvent
from app.models.user import User
RABBITMQ_URL = os.getenv("RABBITMQ_URL", "amqp://guest:guest@rabbitmq:5672/")
QUEUE_NAME = "image_tasks"
POLL_INTERVAL_SECONDS = 1
engine = create_async_engine(DATABASE_URL)
session_maker = async_sessionmaker(engine, expire_on_commit=False)
async def recover_expired_lease():
now = datetime.now(timezone.utc)
async with session_maker() as session:
async with session.begin():
result = await session.execute(
select(Attachment)
.where(
Attachment.status == "processing",
Attachment.lease_expires_at.is_not(None),
Attachment.lease_expires_at <= now,
)
.order_by(Attachment.lease_expires_at)
.limit(1)
.with_for_update(skip_locked=True)
)
att = result.scalar_one_or_none()
if att is None:
return False
att.status = "queued"
att.lease_expires_at = None
session.add(
OutboxEvent(attachment_id=att.id)
)
attachment_id = att.id
print(f"[Outbox] Recovered expired lease: {attachment_id}", flush=True)
return True
async def dispatch_one(channel):
async with session_maker() as session:
async with session.begin():
result = await session.execute(
select(OutboxEvent)
.where(OutboxEvent.published_at.is_(None))
.order_by(OutboxEvent.created_at, OutboxEvent.id)
.limit(1)
.with_for_update(skip_locked=True)
)
event = result.scalar_one_or_none()
if event is None:
return False
confirmation = await channel.default_exchange.publish(
aio_pika.Message(
body=json.dumps(
{"attachment_id": str(event.attachment_id)}
).encode(),
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=str(event.id),
content_type="application/json",
),
routing_key=QUEUE_NAME,
mandatory=True,
)
if confirmation is False:
raise RuntimeError("RabbitMQ did not confirm publication")
event.published_at = datetime.now(timezone.utc)
print(f"[Outbox] Published {event.attachment_id}", flush=True)
return True
async def main():
try:
while True:
try:
connection = await aio_pika.connect_robust(RABBITMQ_URL)
async with connection:
channel = await connection.channel(
publisher_confirms=True,
on_return_raises=True,
)
await channel.declare_queue(
QUEUE_NAME,
durable=True,
)
while True:
recovered = await recover_expired_lease()
published = await dispatch_one(channel)
if not recovered and not published:
await asyncio.sleep(POLL_INTERVAL_SECONDS)
except asyncio.CancelledError:
raise
except Exception as exc:
print(
f"[Outbox] Retry after error: {type(exc).__name__}",
flush=True,
)
await asyncio.sleep(2)
finally:
await engine.dispose()
if __name__ == "__main__":
asyncio.run(main())