"""低频状态对账兜底;正常订单同步完全由 order_site 事务 Outbox 驱动。""" from __future__ import annotations import os import threading from loguru import logger from ...database import WorkerSessionLocal _stop_event = threading.Event() _thread: threading.Thread | None = None _lock = threading.Lock() _LAST_TASK_ID = 0 def _interval_seconds() -> int: try: value = int(os.getenv("PLATFORM_FULFILLMENT_RECONCILE_SECONDS", "900")) except ValueError: return 900 return max(60, value) def _run() -> None: global _LAST_TASK_ID from . import service while not _stop_event.is_set(): # 不抢占启动时的 Webhook;首轮延后一分钟。 if _stop_event.wait(min(60, _interval_seconds())): break db = WorkerSessionLocal() try: queued = 0 for _page in range(20): result = service.reconcile_binding_state_outbox( db, limit=500, after_task_id=_LAST_TASK_ID, ) queued += int(result["queued"]) _LAST_TASK_ID = int(result["nextTaskId"]) if not result["hasMore"]: _LAST_TASK_ID = 0 break logger.info( "直播账号履约低频对账完成: outbox_requeued={}", queued, ) except Exception as exc: # noqa: BLE001 - 对账失败等待下一轮 db.rollback() logger.warning("直播账号履约低频对账失败: {}", exc) finally: db.close() if _stop_event.wait(_interval_seconds()): break def start_platform_fulfillment_reconciler() -> bool: global _thread with _lock: if _thread is not None and _thread.is_alive(): return False _stop_event.clear() _thread = threading.Thread( target=_run, name="platform-fulfillment-reconciler", daemon=True, ) _thread.start() return True def stop_platform_fulfillment_reconciler() -> None: global _thread _stop_event.set() with _lock: thread = _thread _thread = None if thread is not None and thread.is_alive(): thread.join(timeout=3)