mirror of
https://github.com/dat515-2025/Group-8.git
synced 2026-03-22 15:12:08 +01:00
feat(infrastructure): use celery worker
This commit is contained in:
@@ -1,35 +1,28 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
import asyncio
|
||||
# Route email jobs via Celery instead of raw RabbitMQ publishing
|
||||
# Ensure Celery app is initialized so producers use correct broker credentials.
|
||||
# Import has side effects (sets Celery default app), safe to keep at module level.
|
||||
import app.celery_app # noqa: F401
|
||||
|
||||
RABBITMQ_URL = os.getenv("RABBITMQ_URL") or (
|
||||
f"amqp://{os.getenv('RABBITMQ_USERNAME', 'user')}:"
|
||||
f"{os.getenv('RABBITMQ_PASSWORD', 'bitnami123')}@"
|
||||
f"{os.getenv('RABBITMQ_HOST', 'localhost')}:"
|
||||
f"{os.getenv('RABBITMQ_PORT', '5672')}"
|
||||
)
|
||||
QUEUE_NAME = os.getenv("MAIL_QUEUE", "mail_queue")
|
||||
# Use a lazy proxy so _send_email_task is never None, even if Celery modules
|
||||
# are not yet importable at import time (e.g., different working dir during startup).
|
||||
class _LazySendTask:
|
||||
def delay(self, to: str, subject: str, body: str): # type: ignore[no-untyped-def]
|
||||
# Late import on first use
|
||||
from app.workers.celery_tasks import send_email_fields as _send # type: ignore
|
||||
return _send.delay(to, subject, body)
|
||||
|
||||
|
||||
try:
|
||||
# Try eager import for normal operation
|
||||
from app.workers.celery_tasks import send_email_fields as _send_email_task # type: ignore
|
||||
except ImportError: # pragma: no cover - fallback lazy import proxy
|
||||
_send_email_task = _LazySendTask() # type: ignore
|
||||
|
||||
async def _publish_async(message: Dict[str, Any]) -> None:
|
||||
import aio_pika
|
||||
connection = await aio_pika.connect_robust(RABBITMQ_URL)
|
||||
try:
|
||||
channel = await connection.channel()
|
||||
await channel.declare_queue(QUEUE_NAME, durable=True)
|
||||
body = json.dumps(message).encode("utf-8")
|
||||
await channel.default_exchange.publish(
|
||||
aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT),
|
||||
routing_key=QUEUE_NAME,
|
||||
)
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
def enqueue_email(to: str, subject: str, body: str) -> None:
|
||||
message = {"type": "email", "to": to, "subject": subject, "body": body}
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
loop.create_task(_publish_async(message))
|
||||
except RuntimeError:
|
||||
asyncio.run(_publish_async(message))
|
||||
"""Enqueue an email job using Celery.
|
||||
|
||||
Keeps the same public API as before.
|
||||
"""
|
||||
_send_email_task.delay(to, subject, body)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user