Files
live-hub-py/web/backend/services/douyu_runner.py
T

379 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""斗鱼活动任务批次执行器(入口聚合;功能域已拆分到 douyu_runner_*.py)。"""
from __future__ import annotations
import time
from concurrent.futures import as_completed
from sqlalchemy.orm import joinedload
from core.douyu import DouyuActivityError
from ..database import WorkerSessionLocal, release_idle_session
from ..models import DouyuTask
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import persist_probe_result, probe_session
from .douyu_runner_bind import BindMixin
from .douyu_runner_core import (
DOUYU_PROXY_TASK_TYPES,
DouyuBatchRunnerCore,
douyu_batch_registry,
)
from .douyu_runner_donate import DonateMixin
from .douyu_runner_gold import GoldMixin
from .douyu_runner_goods import GoodsMixin
from .douyu_runner_manual import ManualMixin
from .douyu_runner_overview import OverviewMixin
from .douyu_runner_xpd import XpdMixin
from .douyu_service import update_account_profile_from_cookie
from .task_runtime import douyu_lane_for_task, submit
# Compatibility alias for tests and integrations that replace the worker
# session factory at the runner boundary.
SessionLocal = WorkerSessionLocal
class DouyuBatchRunner(
DouyuBatchRunnerCore,
BindMixin,
ManualMixin,
OverviewMixin,
GoldMixin,
DonateMixin,
GoodsMixin,
XpdMixin,
):
"""批量执行斗鱼活动任务(功能域 Mixin 聚合 + 批次调度)。"""
def poll_payment_task_once(
self,
db,
task: DouyuTask,
account,
config: dict,
) -> None:
cookie = str(account.cookie or "")
result = dict(task.result or {})
if not cookie:
self._mark_task(
db,
task,
"failed",
"账号 Cookie 已失效,无法继续查询支付到账",
result,
)
return
previous_clients = self._begin_client_tracking()
try:
if task.task_type == "create_gold_qr":
if str(result.get("recharge_channel") or "") == "supplier_api":
amount = int(
result.get("buy_num")
or self._task_payload(task).get("amount")
or self._task_payload(task).get("gold_amount")
or 1
)
self._poll_create_gold_supplier_once(
db,
task,
account,
cookie,
amount=amount,
)
else:
self._poll_create_gold_qr_once(db, task, account, cookie, config)
elif task.task_type == "create_elite_qr":
self._poll_create_elite_qr_once(db, task, account, cookie, config)
elif task.task_type == "create_esports_qr":
self._poll_create_esports_qr_once(db, task, account, cookie, config)
else:
self._mark_task(
db,
task,
"failed",
f"不支持的支付轮询任务: {task.task_type}",
result,
)
finally:
self._end_client_tracking(previous_clients)
def mark_payment_poll_timeout(self, db, task: DouyuTask) -> None:
result = dict(task.result or {})
message = {
"create_gold_qr": "鱼翅支付到账查询超时",
"create_elite_qr": "精英宝典开通到账查询超时",
"create_esports_qr": "电竞手册开通到账查询超时",
}.get(task.task_type, "支付到账查询超时")
self._mark_task(db, task, "failed", message, result)
def _execute_one(self, task_id: int, config: dict, total: int):
self._execute_one_with_slot(task_id, config, total)
def _execute_one_with_slot(self, task_id: int, config: dict, total: int):
with self._counter_lock:
self._task_started_at[int(task_id)] = time.monotonic()
# 阶段一:短事务抢占任务并标记 running,随后立即释放连接
cookie = ""
task_type = ""
account_name = f"task#{task_id}"
current = 0
preflight_db = SessionLocal()
try:
task = (
preflight_db.query(DouyuTask)
.options(joinedload(DouyuTask.account))
.filter(DouyuTask.id == task_id)
.first()
)
if not task or self._stop.is_set():
return
account = task.account
account_name = self._account_name(account)
task_type = str(task.task_type or "")
self._update_task_progress(preflight_db, task, "running", "执行中")
with self._counter_lock:
self._started += 1
current = self._started
self._push_log("info", f"[{current}/{total}] 开始: {account_name}")
# CK 与健康状态都挂在账号上(2026-10-04 CK 解耦)。
cookie = account.cookie or ""
if not cookie:
self._mark_task(preflight_db, task, "failed", "账号没有可用登录 Cookie")
self._push_log("warning", f"[{current}] {account_name} 无 Cookie")
return
finally:
preflight_db.close()
# 阶段二:不持数据库连接做外网 CK 预检和代理探活
cookie_check = probe_session(cookie, checker=check_douyu_cookie)
ck_verdict = str(cookie_check["status"])
prefetched_proxies = (
self._proxies_for_task()
if ck_verdict == "valid" and task_type in DOUYU_PROXY_TASK_TYPES
else None
)
# 阶段三:打开正式执行会话落库预检结论并执行任务处理
worker_db = SessionLocal()
task = None
if isinstance(getattr(worker_db, "info", None), dict):
worker_db.info["managed_worker_session"] = True
try:
task = (
worker_db.query(DouyuTask)
.options(joinedload(DouyuTask.account))
.filter(DouyuTask.id == task_id)
.first()
)
if not task or self._stop.is_set():
return
account = task.account
raw_detail = cookie_check.get("detail")
detail = raw_detail if isinstance(raw_detail, dict) else {}
persist_probe_result(
worker_db,
account,
{
"probe_id": f"douyu_task.preflight:{task_id}:{account.id or 0}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": detail.get("nickname") or "",
"nickname_source": "session",
},
"session": cookie_check,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="douyu_task.preflight",
record_event=False,
commit=True,
update_session=True,
)
if ck_verdict != "valid":
prefix = (
"Cookie 已失效,请重新登录"
if ck_verdict == "invalid"
else "Cookie 状态无法确认"
)
message = f"{prefix}:{cookie_check['message']}"
self._mark_task(worker_db, task, "failed", message)
self._push_log(
"warning", f"[{current}] {self._account_name(account)} {message}"
)
return
update_account_profile_from_cookie(account, cookie)
if worker_db.dirty or worker_db.new or worker_db.deleted:
worker_db.commit()
handler = {
"refresh_esports_goods": self._execute_refresh_esports_goods,
"get_bind_qr": self._execute_get_bind_qr,
"confirm_bind": self._execute_confirm_bind,
"create_elite_qr": self._execute_create_elite_qr,
"query_elite_status": self._execute_query_elite_status,
"prepare_esports_bind": self._execute_prepare_esports_bind,
"get_esports_bind_qr": self._execute_get_esports_bind_qr,
"query_esports_game_name": self._execute_query_esports_game_name,
"confirm_esports_bind": self._execute_confirm_esports_bind,
"create_esports_qr": self._execute_create_esports_qr,
"query_esports_points": self._execute_query_esports_points,
"donate_esports_chicken_gift": self._execute_donate_esports_chicken_gift,
"donate_esports_firework_gift": self._execute_donate_esports_firework_gift,
"create_gold_qr": self._execute_create_gold_qr,
"donate_elite_gift": self._execute_donate_elite_gift,
"query_points": self._execute_query_points,
"lock_goods": self._execute_lock_goods,
"pay_locked_order": self._execute_pay_locked_order,
"exchange_goods": self._execute_exchange_goods,
"exchange_esports_goods": self._execute_exchange_esports_goods,
"query_game_name": self._execute_query_game_name,
"query_change_bind_time": self._execute_query_change_bind_time,
"query_account_overview": self._execute_query_account_overview,
"query_gold_balance": self._execute_query_gold_balance,
"query_exchange_records": self._execute_query_exchange_records,
"prefetch_csrf_token": self._execute_prefetch_csrf_token,
"get_xpd_bind_qr": self._execute_get_xpd_bind_qr,
"query_xpd_bind_info": self._execute_query_xpd_bind_info,
"confirm_xpd_bind": self._execute_confirm_xpd_bind,
"query_xpd_role": self._execute_query_xpd_role,
"refresh_xpd_goods": self._execute_refresh_xpd_goods,
"query_xpd_balance": self._execute_query_xpd_balance,
"query_xpd_fragments": self._execute_query_xpd_fragments,
"query_xpd_purchase_records": self._execute_query_xpd_purchase_records,
"exchange_xpd_goods": self._execute_exchange_xpd_goods,
}.get(task.task_type)
if handler is None:
self._mark_task(worker_db, task, "failed", "不支持的任务类型")
return
self._hook_local.prefetched_proxies = prefetched_proxies
self._hook_local.has_prefetched_proxies = (
ck_verdict == "valid" and task_type in DOUYU_PROXY_TASK_TYPES
)
previous_clients = self._begin_client_tracking()
try:
handler(worker_db, task, account, cookie, config)
finally:
self._end_client_tracking(previous_clients)
self._hook_local.has_prefetched_proxies = False
self._hook_local.prefetched_proxies = None
task = worker_db.get(DouyuTask, task_id) or task
account = task.account
self._push_log(
"success", f"[{current}] {self._account_name(account)} {task.message}"
)
except DouyuActivityError as exc:
active_task = (worker_db.get(DouyuTask, task_id) or task) if task else None
if active_task is not None:
self._mark_task(worker_db, active_task, "failed", str(exc))
self._push_log("warning", f"斗鱼任务失败: {exc}")
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
active_task = (worker_db.get(DouyuTask, task_id) or task) if task else None
if active_task is not None:
self._mark_task(worker_db, active_task, "error", str(exc))
self._push_log("error", f"斗鱼任务异常: {exc}")
finally:
release_idle_session(worker_db)
worker_db.close()
def run(self):
"""执行批次任务。"""
self._push_log("info", f"斗鱼任务批次 {self.batch_id} 开始")
try:
config = self._config_info(self.db)
tasks = (
self.db.query(DouyuTask)
.filter(
DouyuTask.batch_id == self.batch_id, DouyuTask.status == "planned"
)
.order_by(DouyuTask.id.asc())
.all()
)
if not tasks:
self._push_log("warning", "没有可执行的斗鱼任务")
self._push_log("result", "")
return
for task in tasks:
task.status = "pending"
task.message = "等待执行"
self.db.commit()
for task in tasks:
self._push_task_event(task)
task_ids = [int(task.id) for task in tasks]
# 批次调度阶段后续只等待各任务子槽完成,不再使用外层会话;
# 尽早释放连接,避免阻塞期间白占连接池。
if getattr(self, "close_db", True):
self.db.close()
total = len(task_ids)
lane = douyu_lane_for_task(self.task_type)
pending: dict = {}
next_index = 0
while next_index < total or pending:
while (
not self._stop.is_set()
and next_index < total
and len(pending) < self.concurrency
):
task_id = task_ids[next_index]
future = submit(
lane,
self._execute_one,
task_id,
config,
total,
stopped=self._stop.is_set,
)
if future is None:
break
pending[future] = (int(task_id), time.monotonic())
next_index += 1
if not pending:
break
try:
completed = list(as_completed(pending, timeout=0.5))
except TimeoutError:
continue
for future in completed:
task_id, submitted_at = pending.pop(future)
started_at = self._task_started_at.pop(int(task_id), None)
try:
future.result()
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._push_log(
"error",
f"Worker 异常 task_id={task_id}: {exc}",
)
else:
waited = (
max(0.0, started_at - submitted_at)
if started_at is not None
else 0.0
)
if waited >= 5:
self._push_log(
"info",
f"任务 task_id={task_id} 在 {lane.value} 槽排队 {waited:.1f}s",
)
if self._stop.is_set():
self._push_log("warning", f"斗鱼任务批次 {self.batch_id} 已停止")
else:
self._push_log("info", f"斗鱼任务批次 {self.batch_id} 完成")
self._push_log("result", "")
finally:
douyu_batch_registry.mark_finished(self.batch_id)
if getattr(self, "close_db", True):
self.db.close()