worker.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import logging
  2. from .service import AiTranslateService, SectionTimeout, LLMFailException, Message
  3. from .decode_dataclass import ns_to_dataclass
  4. from .utils import is_stopped
  5. logger = logging.getLogger(__name__)
  6. def handle_message(redis, ch, method, id, content_type, body, api_url: str, openai_proxy: str, customer_timeout: int):
  7. MaxRetry: int = 3
  8. try:
  9. logger.info("process message start (%s) messages", len(body.payload))
  10. consumer = AiTranslateService(
  11. redis, ch, method, api_url, openai_proxy, customer_timeout)
  12. messages = ns_to_dataclass([body], Message)
  13. consumer.process_translate(id, messages[0])
  14. logger.info(f'message {id} ack')
  15. ch.basic_ack(delivery_tag=method.delivery_tag) # 确认消息
  16. except SectionTimeout as e:
  17. # 时间到了,活还没干完 NACK 并重新入队
  18. logger.warning(
  19. f'time is not enough for complete current message id={id}. requeued')
  20. ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
  21. except LLMFailException as e:
  22. logger.warning(f'message {id} LLMFailException')
  23. ch.basic_nack(delivery_tag=method.delivery_tag,
  24. requeue=False)
  25. except Exception as e:
  26. logger.error(f"error: {e}")
  27. logger.exception("Exception")
  28. # retry
  29. retryKey = f'{redis[1]}/message/retry/{id}'
  30. retry = int(redis[0].get(retryKey)
  31. or 0) if redis[0].exists(retryKey) else 0
  32. if retry > MaxRetry:
  33. logger.warning(f'超过最大重试次数[{MaxRetry}],任务失败 id={id}')
  34. # NACK 丢弃或者进入死信队列
  35. ch.basic_nack(delivery_tag=method.delivery_tag,
  36. requeue=False)
  37. else:
  38. retry = retry+1
  39. redis[0].set(retryKey, retry)
  40. # NACK 并重新入队
  41. logger.warning(f'消息处理错误,重新压入队列 [{retry}/{MaxRetry}]')
  42. ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
  43. finally:
  44. is_stopped()