notifier.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. """Bounded in-memory notification retries, isolated from telemetry workers."""
  2. import hashlib
  3. import json
  4. import logging
  5. import threading
  6. import time
  7. import uuid
  8. from collections import OrderedDict
  9. from core_types import QueryResult, BookResult, AvailabilityStatus
  10. from toolkit.cloud_api import CloudApi
  11. _worker_lock = threading.Lock()
  12. _pending_lock = threading.RLock()
  13. _pending = {}
  14. _sent = OrderedDict()
  15. _slot_states = {}
  16. _MAX_PENDING = 256
  17. _MAX_SENT = 1024
  18. _worker = None
  19. _wakeup = threading.Event()
  20. def start_notification_worker():
  21. global _worker
  22. with _worker_lock:
  23. if _worker is None or not _worker.is_alive():
  24. def run():
  25. while True:
  26. try:
  27. _flush_pending(CloudApi.Instance(), logging.getLogger(__name__).warning)
  28. except Exception:
  29. logging.getLogger(__name__).exception('Notification delivery retry failed')
  30. _wakeup.wait(5)
  31. _wakeup.clear()
  32. _worker = threading.Thread(target=run, name='NotificationDelivery', daemon=True)
  33. _worker.start()
  34. _wakeup.set()
  35. def _flush_pending(cloud, logger):
  36. with _pending_lock:
  37. jobs = [(key, value) for key, value in _pending.items() if value[2] <= time.time()][:20]
  38. for event_id, (content, attempts, due) in jobs:
  39. try:
  40. cloud.push_weixin_text(content)
  41. except Exception as exc:
  42. with _pending_lock:
  43. _pending[event_id] = (content, attempts + 1, time.time() + min(300, 5 * 2 ** min(attempts, 6)))
  44. logger(f'Notification retry pending ({event_id}): {exc}')
  45. else:
  46. with _pending_lock:
  47. _pending.pop(event_id, None)
  48. _sent[event_id] = None
  49. while len(_sent) > _MAX_SENT:
  50. _sent.popitem(last=False)
  51. def enqueue_text(event_id, content, logger=None):
  52. with _pending_lock:
  53. if event_id in _pending or event_id in _sent:
  54. return True
  55. if len(_pending) >= _MAX_PENDING:
  56. (logger or logging.getLogger(__name__).error)('Notification queue full; message was not queued')
  57. return False
  58. _pending[event_id] = (content, 0, 0)
  59. _wakeup.set()
  60. return True
  61. def notify_date_changes(query_result: QueryResult, cache=None, logger=None) -> bool:
  62. apt = query_result.apt_type
  63. if not apt or not apt.routing_key:
  64. return False
  65. active = query_result.success or query_result.availability_status in (
  66. AvailabilityStatus.Available, AvailabilityStatus.Waitlist)
  67. snapshot = query_result.to_snapshot_payload()
  68. state = {
  69. 'status': query_result.availability_status.value if active else AvailabilityStatus.NoneAvailable.value,
  70. 'earliest': snapshot['earliest_date'] if active else None,
  71. 'availability': sorted(snapshot['availability'], key=lambda item: json.dumps(item, sort_keys=True)) if active else [],
  72. }
  73. for item in state['availability']:
  74. if 'times' in item:
  75. item['times'] = sorted(item['times'], key=lambda slot: json.dumps(slot, sort_keys=True))
  76. fingerprint = json.dumps(state, sort_keys=True)
  77. content = None
  78. if active:
  79. content = (f"📢【档期变化通知】\n状态: {state['status']}\n"
  80. f"检测时间: {snapshot['snapshot_at']}\n"
  81. f"最早日期: {query_result.earliest_date or '候补/待确认'}\n"
  82. f"目标国家: {apt.country}\n递交城市: {apt.city}\n"
  83. f"签证类型: {apt.visa_type}\nRouting: {apt.routing_key}")
  84. states = cache if cache is not None else _slot_states
  85. with _pending_lock:
  86. if states.get(apt.routing_key) == fingerprint:
  87. return False
  88. if not content:
  89. states[apt.routing_key] = fingerprint
  90. return False
  91. queued = enqueue_text('slot:' + uuid.uuid4().hex, content, logger)
  92. if queued:
  93. states[apt.routing_key] = fingerprint
  94. return queued
  95. def notify_book_result(book_result: BookResult, order_id=None, logger=None, event_id=None) -> bool:
  96. if not book_result.success:
  97. return False
  98. content = (f"🎉 【预定成功通知】\n订单编号: {order_id or '-'}\n"
  99. f"预约账号: {book_result.account}\n预约日期: {book_result.book_date}\n"
  100. f"预约时间: {book_result.book_time}\n预约编号: {book_result.urn}\n"
  101. f"支付链接: {book_result.payment_link or '无需支付/暂无'}")
  102. identity = json.dumps([order_id, book_result.model_dump()], sort_keys=True)
  103. event_id = event_id or 'booking:' + hashlib.sha256(identity.encode()).hexdigest()
  104. return enqueue_text(event_id, content, logger)