"""自动为待处理直播账号履约任务选号;异常任务保留给人工处理。""" from __future__ import annotations import os import threading from datetime import UTC, datetime, timedelta from typing import Any from loguru import logger from sqlalchemy.orm import Session from ...database import SessionLocal from ...models import PlatformFulfillmentTask from . import service DEFAULT_INTERVAL_SECONDS = 20 DEFAULT_BATCH_SIZE = 2 DEFAULT_RETRY_SECONDS = 45 _stop_event = threading.Event() _thread: threading.Thread | None = None _lock = threading.Lock() def _env_int(name: str, default: int, minimum: int, maximum: int) -> int: try: value = int(os.getenv(name, str(default))) except ValueError: return default return max(minimum, min(maximum, value)) def run_auto_allocation_once( db: Session, *, limit: int | None = None, now: datetime | None = None, ) -> dict[str, int]: """扫描 ready 且尚未分配账号的任务,逐笔调用统一选号逻辑。""" moment = now or datetime.now(UTC) batch_size = limit or _env_int( "PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH", DEFAULT_BATCH_SIZE, 1, 20, ) retry_seconds = _env_int( "PLATFORM_FULFILLMENT_AUTO_ALLOCATE_RETRY_SECONDS", DEFAULT_RETRY_SECONDS, 10, 3600, ) query = db.query(PlatformFulfillmentTask).filter( PlatformFulfillmentTask.execution_status == "ready", PlatformFulfillmentTask.account_id.is_(None), PlatformFulfillmentTask.commodity_id != "", PlatformFulfillmentTask.updated_at <= moment - timedelta(seconds=retry_seconds), ) match_started_at = service._order_match_started_at(db) if match_started_at is not None: query = query.filter( PlatformFulfillmentTask.created_at >= match_started_at, ) candidates = ( query.order_by(PlatformFulfillmentTask.updated_at.asc()).limit(batch_size).all() ) if not candidates: return {"checked": 0, "allocated": 0, "failed": 0} actor = service._integration_actor(db) allocated = 0 failed = 0 for task in candidates: try: detail: dict[str, Any] = service.allocate_task( db, task_id=int(task.id), current=actor, ) if detail.get("task", {}).get("account"): allocated += 1 else: failed += 1 except Exception as exc: # noqa: BLE001 - 单个任务异常不能中断整批 db.rollback() failed += 1 logger.warning("直播账号履约自动选号失败 task_id={}: {}", task.id, exc) return { "checked": len(candidates), "allocated": allocated, "failed": failed, } def _run() -> None: interval = _env_int( "PLATFORM_FULFILLMENT_AUTO_ALLOCATE_SECONDS", DEFAULT_INTERVAL_SECONDS, 5, 3600, ) while not _stop_event.wait(interval): db = SessionLocal() try: result = run_auto_allocation_once(db) if result["checked"]: logger.info("直播账号履约自动选号: {}", result) except Exception as exc: # noqa: BLE001 - worker 不能因单轮异常退出 db.rollback() logger.warning("直播账号履约自动选号轮次失败: {}", exc) finally: db.close() def start_platform_fulfillment_auto_allocator() -> 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-auto-allocator", daemon=True, ) _thread.start() return True def stop_platform_fulfillment_auto_allocator() -> 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)