Complete lab 5 asynchronous image processing
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
"""Publish durable PostgreSQL outbox events to RabbitMQ.
|
||||
|
||||
The database row is marked published only after RabbitMQ publisher confirmation.
|
||||
If the process crashes after broker confirmation but before the DB commit, the
|
||||
same event is published again; consumers must therefore be idempotent.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import aio_pika
|
||||
from aio_pika import DeliveryMode, Message
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.models import OutboxEvent
|
||||
from app.db.session import SessionLocal
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
async def publish_once() -> int:
|
||||
"""Publish one batch; return number of confirmed events."""
|
||||
connection = await aio_pika.connect_robust(settings.rabbitmq_url)
|
||||
try:
|
||||
channel = await connection.channel(publisher_confirms=True)
|
||||
exchange = await channel.declare_exchange(
|
||||
settings.rabbitmq_exchange,
|
||||
aio_pika.ExchangeType.DIRECT,
|
||||
durable=True,
|
||||
)
|
||||
queue = await channel.declare_queue(settings.rabbitmq_queue, durable=True)
|
||||
await queue.bind(exchange, routing_key=settings.rabbitmq_queue)
|
||||
|
||||
published = 0
|
||||
db: Session = SessionLocal()
|
||||
try:
|
||||
# Lock a bounded batch. SKIP LOCKED allows multiple publisher replicas.
|
||||
events = db.scalars(
|
||||
select(OutboxEvent)
|
||||
.where(OutboxEvent.status == "pending")
|
||||
.order_by(OutboxEvent.created_at)
|
||||
.with_for_update(skip_locked=True)
|
||||
.limit(settings.outbox_batch_size)
|
||||
).all()
|
||||
|
||||
for event in events:
|
||||
body = json.dumps(event.payload, separators=(",", ":")).encode("utf-8")
|
||||
message = Message(
|
||||
body=body,
|
||||
content_type="application/json",
|
||||
delivery_mode=DeliveryMode.PERSISTENT,
|
||||
message_id=str(event.id),
|
||||
type=event.event_type,
|
||||
timestamp=utc_now(),
|
||||
)
|
||||
await exchange.publish(message, routing_key=settings.rabbitmq_queue, mandatory=True)
|
||||
event.status = "published"
|
||||
event.published_at = utc_now()
|
||||
event.attempts += 1
|
||||
published += 1
|
||||
|
||||
db.commit()
|
||||
return published
|
||||
except Exception:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
async def run_publisher() -> None:
|
||||
delay = settings.outbox_poll_interval_seconds
|
||||
while True:
|
||||
try:
|
||||
count = await publish_once()
|
||||
if count:
|
||||
logger.info("Published %s outbox events", count)
|
||||
delay = settings.outbox_poll_interval_seconds
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception("Outbox publisher iteration failed")
|
||||
delay = min(max(delay * 2, settings.outbox_poll_interval_seconds), 15.0)
|
||||
delay += random.uniform(0, delay * 0.2)
|
||||
await asyncio.sleep(delay)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
asyncio.run(run_publisher())
|
||||
Reference in New Issue
Block a user