"""低频订单对账兜底;正常同步由 order_site 签名 Webhook 驱动。""" from __future__ import annotations import os import threading from loguru import logger from ...database import SessionLocal _stop_event = threading.Event() _thread: threading.Thread | None = None _lock = threading.Lock() 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: from . import service while not _stop_event.is_set(): # 不抢占启动时的 Webhook;首轮延后一分钟。 if _stop_event.wait(min(60, _interval_seconds())): break db = SessionLocal() try: result = service.sync_pending_tasks(db, limit=500) queued = service.reconcile_binding_state_outbox(db, limit=500) logger.info( "直播账号履约低频对账完成: order_sync={} outbox_requeued={}", result, 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)