|
| 1 | +""" |
| 2 | +AMQP Domain Event Consumer (Kombu) |
| 3 | +
|
| 4 | +Alert Service가 도메인 이벤트를 직접 구독하여 자율적으로 처리. |
| 5 | +Choreography: 각 서비스는 이벤트에 독립적으로 반응한다. |
| 6 | +
|
| 7 | +Main Service를 거치지 않고 Alert Service가 직접 |
| 8 | +detections.completed 이벤트를 구독하여 알림 발송 여부를 결정한다. |
| 9 | +""" |
| 10 | + |
| 11 | +import json |
| 12 | +import logging |
| 13 | +import os |
| 14 | +import time |
| 15 | + |
| 16 | +from kombu import Connection, Exchange, Queue |
| 17 | +from kombu.mixins import ConsumerMixin |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | +DOMAIN_EVENTS_EXCHANGE = Exchange("domain_events", type="topic", durable=True) |
| 22 | + |
| 23 | + |
| 24 | +class AlertEventConsumer(ConsumerMixin): |
| 25 | + """ |
| 26 | + Alert Service 도메인 이벤트 소비자 |
| 27 | +
|
| 28 | + detections.completed 이벤트를 구독하고, |
| 29 | + Alert Service가 자율적으로 알림 발송 여부를 결정한다. |
| 30 | + OCR Service의 존재도, Main Service의 중개도 모른다. |
| 31 | + """ |
| 32 | + |
| 33 | + def __init__(self, connection): |
| 34 | + self.connection = connection |
| 35 | + |
| 36 | + def get_consumers(self, Consumer, channel): |
| 37 | + queue = Queue( |
| 38 | + "alert_domain_events", |
| 39 | + exchange=DOMAIN_EVENTS_EXCHANGE, |
| 40 | + routing_key="detections.completed", |
| 41 | + durable=True, |
| 42 | + queue_arguments={ |
| 43 | + "x-dead-letter-exchange": "dlq_exchange", |
| 44 | + }, |
| 45 | + ) |
| 46 | + return [ |
| 47 | + Consumer( |
| 48 | + queues=[queue], |
| 49 | + callbacks=[self.on_event], |
| 50 | + accept=["json"], |
| 51 | + ) |
| 52 | + ] |
| 53 | + |
| 54 | + def on_event(self, body, message): |
| 55 | + """도메인 이벤트 수신 및 처리""" |
| 56 | + try: |
| 57 | + payload = json.loads(body) if isinstance(body, str) else body |
| 58 | + routing_key = message.delivery_info.get("routing_key", "") |
| 59 | + |
| 60 | + if routing_key == "detections.completed": |
| 61 | + self._on_detection_completed(payload) |
| 62 | + |
| 63 | + message.ack() |
| 64 | + except Exception as e: |
| 65 | + logger.error(f"Failed to process domain event: {e}") |
| 66 | + message.reject(requeue=False) |
| 67 | + |
| 68 | + def _on_detection_completed(self, payload): |
| 69 | + """ |
| 70 | + detections.completed 이벤트에 반응 |
| 71 | +
|
| 72 | + Alert Service의 자율적 판단: |
| 73 | + "OCR이 완료됐으니 알림을 보내야겠다" |
| 74 | + """ |
| 75 | + detection_id = payload["detection_id"] |
| 76 | + logger.info( |
| 77 | + f"Detection {detection_id} completed event received — " |
| 78 | + f"processing notification" |
| 79 | + ) |
| 80 | + |
| 81 | + max_retries = 3 |
| 82 | + for attempt in range(max_retries + 1): |
| 83 | + try: |
| 84 | + from tasks.notification_tasks import process_notification |
| 85 | + |
| 86 | + process_notification(detection_id) |
| 87 | + return |
| 88 | + except Exception as e: |
| 89 | + if "DoesNotExist" in type(e).__name__ and attempt < max_retries: |
| 90 | + logger.warning( |
| 91 | + f"Detection {detection_id} not ready, " |
| 92 | + f"retry {attempt + 1}/{max_retries}" |
| 93 | + ) |
| 94 | + time.sleep(3) |
| 95 | + else: |
| 96 | + raise |
| 97 | + |
| 98 | + |
| 99 | +def start_event_consumer(): |
| 100 | + """Alert Service 도메인 이벤트 소비자 시작 (blocking)""" |
| 101 | + broker_url = os.getenv("CELERY_BROKER_URL", "amqp://guest:guest@rabbitmq:5672//") |
| 102 | + logger.info(f"Starting Alert Event Consumer on {broker_url}") |
| 103 | + |
| 104 | + with Connection(broker_url) as conn: |
| 105 | + consumer = AlertEventConsumer(conn) |
| 106 | + consumer.run() |
0 commit comments