"""持久执行任务的 worker 消费循环。""" from __future__ import annotations import os import threading from concurrent.futures import Future, ThreadPoolExecutor, wait from datetime import UTC, datetime from typing import Any from loguru import logger from ..database import WorkerSessionLocal from ..models import DouyuTask, ExecutionJob, ProxyConfig, User from ..permissions import get_user_permissions from .douyu_runner import DouyuBatchRunner from .execution_jobs import ( JOB_DOUYU_BATCH, JOB_DOUYU_BINDING, JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH, LANE_AUTH, LANE_FULFILLMENT, STATUS_CANCELLED, STATUS_SUCCEEDED, append_execution_event, claim_execution_jobs, execution_worker_owner, fail_execution_job, finish_execution_job, heartbeat_execution_job, ) from .login_service import LoginBatchRunner DEFAULT_EXECUTION_WORKERS = 2 DEFAULT_POLL_SECONDS = 1 def _env_positive_int(name: str, default: int, minimum: int = 1) -> int: try: value = int(os.getenv(name, str(default))) except ValueError: return default return max(minimum, value) def _lane_scopes() -> tuple[str, ...]: raw = os.getenv("EXECUTION_WORKER_LANES", "auth,fulfillment") allowed = {LANE_AUTH, LANE_FULFILLMENT} scopes = tuple( item.strip().lower() for item in raw.split(",") if item.strip().lower() in allowed ) return scopes or (LANE_AUTH, LANE_FULFILLMENT) class ExecutionJobWorker: def __init__(self) -> None: self._stop = threading.Event() self._thread: threading.Thread | None = None self._lock = threading.Lock() self._executor: ThreadPoolExecutor | None = None self._owner = execution_worker_owner() def start(self) -> bool: with self._lock: if self._thread is not None and self._thread.is_alive(): return False self._stop.clear() max_workers = _env_positive_int( "EXECUTION_WORKER_MAX_JOBS", DEFAULT_EXECUTION_WORKERS, ) self._executor = ThreadPoolExecutor( max_workers=max_workers, thread_name_prefix="execution-job", ) self._thread = threading.Thread( target=self._run, name="execution-job-consumer", daemon=True, ) self._thread.start() logger.info( "执行任务 worker 已启动 lanes={} max_jobs={}", ",".join(_lane_scopes()), max_workers, ) return True def stop(self) -> None: self._stop.set() with self._lock: thread = self._thread executor = self._executor self._thread = None self._executor = None if thread is not None and thread.is_alive(): thread.join(timeout=5) if executor is not None: executor.shutdown(wait=True, cancel_futures=True) def _run(self) -> None: futures: set[Future] = set() max_jobs = _env_positive_int( "EXECUTION_WORKER_MAX_JOBS", DEFAULT_EXECUTION_WORKERS, ) poll_seconds = _env_positive_int( "EXECUTION_WORKER_POLL_SECONDS", DEFAULT_POLL_SECONDS, ) while not self._stop.is_set(): futures = {future for future in futures if not future.done()} executor = self._executor if executor is None: break slots = max_jobs - len(futures) if slots > 0: try: jobs = claim_execution_jobs( lane_scopes=_lane_scopes(), owner=self._owner, limit=slots, ) except Exception: # noqa: BLE001 - 消费循环必须存活 logger.exception("领取执行任务失败") jobs = [] for job in jobs: futures.add(executor.submit(self._run_job, job.id)) if futures: wait(futures, timeout=poll_seconds) else: self._stop.wait(poll_seconds) def _run_job(self, job_id: int) -> None: db = WorkerSessionLocal() job: ExecutionJob | None = None runner: Any = None cancelled = threading.Event() heartbeat_stop = threading.Event() try: job = db.get(ExecutionJob, int(job_id)) if job is None or job.status != "running": return payload = dict(job.payload_json or {}) user = db.get(User, int(job.created_by)) if user is None: raise RuntimeError("执行任务创建人不存在") def log_sink(event: dict[str, Any]) -> None: event_payload = dict(event) level = str(event_payload.pop("level", "info") or "info") message = str(event_payload.pop("message", "") or "") append_execution_event( job_id=int(job.id), batch_id=job.batch_id, level=level, message=message, payload=event_payload or None, ) def heartbeat_loop() -> None: while not heartbeat_stop.wait(5): if self._stop.is_set(): cancelled.set() if runner is not None: runner.stop() return held, cancel_requested = heartbeat_execution_job( job_id=int(job.id), owner=self._owner, ) if not held: cancelled.set() return if cancel_requested and not cancelled.is_set(): cancelled.set() if runner is not None: runner.stop() log_sink( { "level": "warning", "message": "收到停止请求,正在安全收尾", } ) heartbeat = threading.Thread( target=heartbeat_loop, name=f"execution-heartbeat-{job.id}", daemon=True, ) heartbeat.start() summary: dict[str, Any] = {} if job.job_type in {JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH}: proxy = db.query(ProxyConfig).first() runner = LoginBatchRunner( db=db, account_ids=[ int(value) for value in payload.get("account_ids", []) ], created_by=int(job.created_by), creator_permissions=get_user_permissions(user), max_login_retries=int(payload.get("max_login_retries", 0) or 0), max_total_time=float(payload.get("max_total_time", 300) or 0), proxy_config=proxy, log_queue=None, loop=None, concurrency=int(payload.get("concurrency", 3) or 3), api_strategy=str(payload.get("api_strategy", "wgapi") or "wgapi"), mode=str(payload.get("mode", "login") or "login"), trigger_source=str(payload.get("trigger_source", "manual") or "manual"), batch_id=job.batch_id, log_sink=log_sink, ) runner.run() elif job.job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}: if int(job.attempt_count or 0) > 1: # 进程中断会留下 pending/running 的初始任务;支付轮询有独立 # queue_lane,不能被重放。重试只重置尚无后置 lane 的行。 db.query(DouyuTask).filter( DouyuTask.batch_id == job.batch_id, DouyuTask.status.in_(("planned", "pending", "running")), DouyuTask.queue_lane == "", ).update( { DouyuTask.status: "planned", DouyuTask.message: "执行进程中断,已恢复排队", }, synchronize_session=False, ) db.commit() runner = DouyuBatchRunner( db=db, batch_id=job.batch_id, task_type=str(payload.get("task_type") or ""), payload=dict(payload.get("payload") or {}), log_queue=None, loop=None, concurrency=int(payload.get("concurrency", 3) or 3), close_db=False, log_sink=log_sink, ) runner.run() else: raise RuntimeError(f"不支持的执行任务类型: {job.job_type}") summary = {"finished_at": datetime.now(UTC).isoformat()} held, cancel_requested = heartbeat_execution_job( job_id=int(job.id), owner=self._owner, ) if not held: return finish_execution_job( job_id=int(job.id), owner=self._owner, status=( STATUS_CANCELLED if cancelled.is_set() or cancel_requested else STATUS_SUCCEEDED ), summary=summary, ) except Exception as exc: # noqa: BLE001 - job 边界必须收口 logger.exception("执行任务失败 job_id={}", job_id) append_execution_event( job_id=int(job_id), batch_id=str(job.batch_id) if job is not None else "", level="error", message=f"{type(exc).__name__}: {exc}", ) fail_execution_job( job_id=int(job_id), owner=self._owner, error=f"{type(exc).__name__}: {exc}", ) finally: heartbeat_stop.set() db.close() execution_job_worker = ExecutionJobWorker() def start_execution_job_worker() -> bool: return execution_job_worker.start() def stop_execution_job_worker() -> None: execution_job_worker.stop() def execution_job_worker_status() -> dict[str, Any]: thread = execution_job_worker._thread return { "running": bool(thread and thread.is_alive()), "lanes": list(_lane_scopes()), "max_jobs": _env_positive_int( "EXECUTION_WORKER_MAX_JOBS", DEFAULT_EXECUTION_WORKERS, ), "owner": execution_job_worker._owner, } __all__ = [ "execution_job_worker_status", "start_execution_job_worker", "stop_execution_job_worker", ]