"""登录服务:复用 core/ 核心模块,在线程池中并发执行登录并推送日志。""" import asyncio import os import threading import time import uuid from collections.abc import Callable from concurrent.futures import as_completed from datetime import UTC, datetime from types import SimpleNamespace from typing import Any, cast from loguru import logger from sqlalchemy import and_, func, or_ from sqlalchemy.orm import Session, object_session from core.douyu import DouyuLogin, create_login_api_strategy from core.douyu.login import AccountLike from ..models import Account as AccountModel from ..models import LoginAttempt, LoginTask from ..models import ProxyConfig as ProxyConfigModel from .account_events_service import ( EVENT_LOGIN_FAILED, EVENT_LOGIN_OK, EVENT_RELOGIN_OK, emit, ) from .account_lifecycle import on_login_success, sync_status from .account_sync_service import DOMAIN_STOREHOME, mark_domain_dirty from .account_work_queue import enqueue_account_work from .cookie_check_service import check_douyu_cookie from .douyu_account_probe import persist_probe_result, probe_session from .douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES from .login_failure import classify_failure, failure_kind_label, is_account_fault from .login_quota_service import ( finish_login_attempt, login_concurrency_limit, reserve_login_attempt, ) from .proxy_service import build_proxy_runtime from .task_runtime import TaskLane, submit # ── 逐账号全量日志 ──────────────────────────────────────────────── # core/ 里的登录实现直接用 loguru 打日志(步骤 1~7、代理预检、极验、邮箱取码…), # 不经过 LoginBatchRunner。页面要看的「这个账号到底卡在哪一步」恰恰就在那些 # 记录里,所以这里挂一个 loguru sink,按线程把日志归到当前登录任务上。 _LOG_CONTEXT = threading.local() _TASK_LOG_SINK_ID: int | None = None _TASK_LOG_SINK_LOCK = threading.Lock() # 进行中的任务日志放在模块字典里(而不是线程局部):页面要看「正在登录」的 # 实时进度,必须由独立的刷新线程能读到登录线程写的内容。 _TASK_LOGS: dict[int, list[dict[str, Any]]] = {} _TASK_LOGS_LOCK = threading.Lock() # 刷新线程和登录线程都会写 login_tasks.logs。没有这把锁时,刷新线程可能拿着 # 「较早的快照」在收尾写库之后提交,把最后几条(往往正是失败原因)覆盖掉。 # 所有落库动作都在这把锁内完成「取快照 + 写库」,保证收尾那一笔一定是最后写入。 _TASK_LOG_PERSIST_LOCK = threading.Lock() _TASK_LOG_FLUSHER: threading.Thread | None = None _TASK_LOG_FLUSH_SECONDS = 3.0 # 单任务最多保留条数;超出后优先丢 DEBUG,避免把关键步骤挤掉。 TASK_LOG_LIMIT = 300 TASK_LOG_MESSAGE_LIMIT = 1200 _TASK_LOG_BATCH_PREFIX = "[登录批次 " def _append_task_log(level: str, message: str, module: str = "") -> None: task_id = int(getattr(_LOG_CONTEXT, "task_id", 0) or 0) if not task_id: return text = str(message or "").strip() if not text: return # 批次级前缀对单账号日志没有意义,这里剥掉。 if text.startswith(_TASK_LOG_BATCH_PREFIX): end = text.find("] ") if end > 0: text = text[end + 2 :].strip() entry = { "level": level, "message": text[:TASK_LOG_MESSAGE_LIMIT], "module": module, "at": datetime.now(UTC).isoformat(), } with _TASK_LOGS_LOCK: logs = _TASK_LOGS.setdefault(task_id, []) logs.append(entry) if len(logs) > TASK_LOG_LIMIT: for index, item in enumerate(logs): if item.get("level") == "debug": del logs[index] break else: del logs[0] def _snapshot_task_logs(task_id: int) -> list[dict[str, Any]]: with _TASK_LOGS_LOCK: return list(_TASK_LOGS.get(task_id, ())) def _drop_task_logs(task_id: int) -> list[dict[str, Any]]: with _TASK_LOGS_LOCK: return _TASK_LOGS.pop(task_id, []) def _task_log_entry(level: str, message: str, module: str = "login_service") -> dict: """构造一条要直接落库的日志(不经过登录线程的 loguru sink)。""" return { "level": level, "message": str(message or "").strip()[:TASK_LOG_MESSAGE_LIMIT], "module": module, "at": datetime.now(UTC).isoformat(), } def _append_persisted_log( task: LoginTask, level: str, message: str, module: str = "login_service", ) -> None: """给「没有进入登录线程」的尝试补一条说明日志(跳过、停止、异常收尾)。 这类账号以前什么都不写:页面上既没有任务行也没有日志,运营只看到 「点了登录没反应」。现在至少能看到一行原因。 """ entry = _task_log_entry(level, message, module) if not entry["message"]: return existing = [item for item in (task.logs or []) if isinstance(item, dict)] task.logs = (existing + [entry])[-TASK_LOG_LIMIT:] def _flush_active_task_logs() -> None: """把进行中的任务日志增量写库,页面就能看到实时进度。""" with _TASK_LOGS_LOCK: task_ids = list(_TASK_LOGS) for task_id in task_ids: # 锁内重新确认任务仍在进行中:收尾线程可能刚把日志取走并落库, # 这里再写一次旧快照就会覆盖掉最后的失败原因。 with _TASK_LOG_PERSIST_LOCK: logs = _snapshot_task_logs(task_id) if logs: _persist_task_logs(task_id, logs) def _start_task_log_flusher() -> None: global _TASK_LOG_FLUSHER if _TASK_LOG_FLUSHER is not None and _TASK_LOG_FLUSHER.is_alive(): return with _TASK_LOG_SINK_LOCK: if _TASK_LOG_FLUSHER is not None and _TASK_LOG_FLUSHER.is_alive(): return def loop() -> None: while True: time.sleep(_TASK_LOG_FLUSH_SECONDS) try: _flush_active_task_logs() except Exception: # noqa: BLE001 - 刷新线程必须存活 logger.exception("刷新登录任务日志失败") _TASK_LOG_FLUSHER = threading.Thread( target=loop, name="login-task-log-flusher", daemon=True ) _TASK_LOG_FLUSHER.start() def _task_log_sink(message: Any) -> None: record = getattr(message, "record", None) if record is None: return _append_task_log( str(record["level"].name or "info").lower(), str(record["message"] or ""), str((record.get("name") or "").split(".")[-1]), ) def _install_task_log_sink() -> None: """全局只挂一个 sink;重复构造 runner 不会重复记录。""" global _TASK_LOG_SINK_ID if _TASK_LOG_SINK_ID is not None: return with _TASK_LOG_SINK_LOCK: if _TASK_LOG_SINK_ID is not None: return _TASK_LOG_SINK_ID = logger.add( _task_log_sink, level="DEBUG", format="{message}", enqueue=False, backtrace=False, diagnose=False, ) def _persist_task_logs(task_id: int, logs: list[dict[str, Any]]) -> None: """用独立短事务写日志,避免和登录事务互相影响。""" if not logs: return session = WorkerSessionLocal() try: task = session.query(LoginTask).filter(LoginTask.id == task_id).first() if task is None: return task.logs = logs[-TASK_LOG_LIMIT:] session.commit() except Exception: # noqa: BLE001 - 日志落库失败不能掩盖登录结果 session.rollback() logger.exception("保存登录账号日志失败: task_id={}", task_id) finally: session.close() CHECK_STATUS_MESSAGES = { "account_cancelled": "账号已注销", "password_wrong": "账号密码错误", "account_unverified": "账号未认证", "account_verified": "账号已认证", "account_auth_unknown": "账号认证状态未知", } CHECK_STATUS_LOG_LEVELS = { "account_cancelled": "warning", "password_wrong": "error", "account_unverified": "warning", "account_verified": "success", "account_auth_unknown": "warning", } def _positive_env_int(name: str, default: int) -> int: """读取正整数环境变量,非法值回退到默认值。""" try: value = int(os.getenv(name, str(default))) except ValueError: return default return value if value > 0 else default def get_relogin_limits() -> tuple[int, int]: """读取客服 CK 重登的重试与总时长限制。""" return ( _positive_env_int("COOKIE_RELOGIN_MAX_RETRIES", 5), # 单账号总时长:要覆盖斗鱼验证码邮件的最坏投递延迟(实测 8~13 分钟) _positive_env_int("COOKIE_RELOGIN_MAX_TOTAL_TIME", 1800), ) def _snapshot_proxy_config( proxy_config: ProxyConfigModel | None, ) -> ProxyConfigModel | None: """复制代理配置,避免后台线程访问已关闭会话中的 ORM 对象。""" if proxy_config is None: return None credentials = getattr(proxy_config, "whitelist_credentials", None) return cast( ProxyConfigModel, SimpleNamespace( enabled=bool(getattr(proxy_config, "enabled", False)), http=getattr(proxy_config, "http", "") or "", https=getattr(proxy_config, "https", "") or "", api_url=getattr(proxy_config, "api_url", "") or "", whitelist_enabled=bool(getattr(proxy_config, "whitelist_enabled", False)), whitelist_platform=getattr(proxy_config, "whitelist_platform", None), whitelist_credentials=dict(credentials) if isinstance(credentials, dict) else credentials, whitelist_uid=getattr(proxy_config, "whitelist_uid", "") or "", whitelist_ukey=getattr(proxy_config, "whitelist_ukey", "") or "", ), ) ATTEMPT_IN_FLIGHT_STATUSES = ("pending", "running") # 升级前把尝试状态写进 status 的历史取值;判断与清理时一并兼容。 _LEGACY_IN_FLIGHT_STATUSES = ( "pending", "running", "relogin_pending", "relogin_running", ) def _attempt_in_flight(task: LoginTask) -> bool: """判断这条记录是否正被某个批次处理(只看尝试字段,不看 CK 字段)。""" if task.attempt_status in ATTEMPT_IN_FLIGHT_STATUSES: return True return not task.attempt_status and task.status in _LEGACY_IN_FLIGHT_STATUSES def _begin_attempt(task: LoginTask, batch_id: str, message: str) -> None: """登记一次登录尝试。 只写 attempt_*:账号当前持有的 CK(status/cookie/message)在登录成功前 一律不动,所以批次被停止、失败或进程重启都不会让账号失去 CK。 """ task.attempt_status = "pending" task.attempt_message = message task.attempt_batch_id = batch_id task.attempt_at = None def _mark_attempt_failed( task: LoginTask, message: str, *, status: str = "failed" ) -> None: """记录一次失败/被中断的尝试;**账号已有的 CK 原样不动**。 这里读的是 `task.account.cookie`(CK 自 2026-10-04 起挂在账号上), 而不是这条登录记录 —— 记录不再持有凭证。 顺带往**账号时间线**写一条失败事件(这是账号级的资产变化:这个账号登录不上)。 两条边界: - **被停止 / 被中断不写**:`classify_failure` 把它们归到 `interrupted`, 那是人的动作或进程重启,不是账号出了状况。不挡住的话, 运营按一次「停止」就能给几十个账号的时间线刷满假失败。 - **幂等**:一次尝试一条(`source_ref` 带 task id + 尝试时刻), 失败重试会新建记录或新 attempt,因此是新的一条 —— 这是对的,那是新的事实。 """ completed_at = datetime.now(UTC) # MySQL DATETIME(0) 会按毫秒四舍五入到整秒。若 source_ref 使用内存里 # 带微秒的原值,第一次写 13:57:13.999 会落成 13:57:14;第二次重读后 # 幂等键变成下一秒,唯一索引就无法拦住重复事件。先截断到整秒再统一使用。 attempt_at = task.attempt_at or completed_at.replace(microsecond=0) attempt_utc = ( attempt_at.replace(tzinfo=UTC) if attempt_at.tzinfo is None else attempt_at.astimezone(UTC) ) task.attempt_status = status if status in {"failed", "error"} else "failed" task.attempt_message = message task.attempt_at = attempt_at account = task.account if not (account and account.cookie): # 账号还没有任何 CK 需要保护:保持旧的失败语义,便于复用记录与页面统计。 task.status = task.attempt_status task.message = message task.finished_at = completed_at kind = classify_failure(message) if not is_account_fault(kind): return db = object_session(task) if db is None or account is None: # 没有会话(纯内存构造的用例)或没有账号:跳过旁路事件,绝不影响主流程。 return account.relogin_failure_kind = kind account.relogin_last_error = (message or "")[:512] sync_status(db, account, occurred_at=completed_at) emit( db, account_id=account.id, event_type=EVENT_LOGIN_FAILED, title=f"登录失败:{message}", occurred_at=attempt_at, detail={ "message": message, "kind": kind, "kind_label": failure_kind_label(kind), "attempt_status": task.attempt_status, }, source="login", subject_type="login", subject_key=kind, source_ref=( f"login_task:{task.id}:failed:{attempt_utc.strftime('%Y%m%dT%H%M%S')}" ), ) def _write_login_success( db: Session, task: LoginTask, *, cookie: str, message: str, batch_id: str, event_type: str = EVENT_LOGIN_OK, ) -> None: """登录成功后把新 CK 写到**账号**上:这是唯一替换旧 CK 的入口。 顺带记一条账号事件 —— CK 是**覆盖式**字段,换掉之后就看不出「这账号什么时候 登录成功过、换过几次 CK」。事件是旁路(emit 内部吞异常),记不上也不影响登录。 """ completed_at = datetime.now(UTC) account = task.account task.status = "success" task.message = message task.batch_id = batch_id task.finished_at = completed_at task.attempt_status = "success" task.attempt_message = message task.attempt_batch_id = batch_id task.attempt_at = completed_at if account is not None: # CK 是**账号级凭证**,不是「某次登录的产物」—— 写账号,不写记录。 account.cookie = cookie account.cookie_updated_at = completed_at account.cookie_source = "web" # 登录成功同时作废上一轮重登的退避痕迹,并把状态重算回正常。 # 人工手动登录也走这条 →「待人工」的账号被人工救回来时状态会正确恢复。 on_login_success(db, account, occurred_at=completed_at) emit( db, account_id=task.account_id, event_type=event_type, title="重新登录成功,Cookie 已更新" if event_type == EVENT_RELOGIN_OK else "登录成功", occurred_at=completed_at, detail={"message": message, "batch_id": batch_id}, source="login", # 幂等键用登录记录 + 完成时间:同一账号多次登录是多个事件, # 但同一次登录重复写回不会重复入库。 source_ref=f"login_task:{task.id}:{int(completed_at.timestamp())}", ) def _enqueue_post_login_sync(db: Session, account: AccountModel) -> None: """登录并验证成功后,把商品能力标脏并进入内部同步队列。""" mark_domain_dirty( db, account_id=int(account.id), domain=DOMAIN_STOREHOME, reason="登录成功,等待同步完整商城商品能力", ) enqueue_account_work( db, account_id=int(account.id), work_type=DOMAIN_STOREHOME + "_sync", priority=20, reason="登录成功联动同步", ) def _persist_login_cookie_verification( db: Session, task: LoginTask, account: AccountModel, check_result: dict, *, batch_id: str, mode: str, ) -> str: """把新 Cookie 的检测结论落到账号。 普通登录与重登共享这一入口。登录成功只证明登录流程拿到了 Cookie,不能 直接复用账号上一次的 CK 结论;必须让本次新 Cookie 形成 ``valid/invalid/error`` 的新鲜判定,分配池才能据此放行。 """ detail = ( check_result.get("detail") if isinstance(check_result.get("detail"), dict) else {} ) persist_probe_result( db, account, { "probe_id": f"login-verify:{batch_id}:{task.id}", "identity": { "uid": account.uid, "username": account.username, "nickname": (detail or {}).get("nickname") or "", "nickname_source": "session", }, "session": check_result, "elite": {}, "eligibility": {}, "roles": {}, "gold": {}, "goods": {}, "errors": {}, }, source="login.verify", record_event=False, commit=False, ) prefix = "重新登录成功" if mode == "relogin" else "登录成功" if check_result.get("status") == "valid": message = f"{prefix},Cookie 有效" else: message = ( f"{prefix},但 Cookie 有效性检测失败: " f"{check_result.get('message') or '状态未知'}" ) task.message = message[:512] task.attempt_message = task.message return task.message def _batch_max_seconds() -> float: """单个登录批次最多占用执行队列槽位的时长(秒);0 表示不限。 登录批次在执行任务队列里占着一个槽。斗鱼邮箱验证码是攒批投递的,等一封 验证码最长 25 分钟/账号,批次没有上限的话 10 个账号能占着槽位跑近一小时, 同队列的斗鱼履约批次会被饿死(新建任务直接报「斗鱼任务繁忙」)。 """ raw = str(os.getenv("LOGIN_BATCH_MAX_SECONDS") or "").strip() if not raw: return 1800.0 try: value = int(raw) except ValueError: return 1800.0 return max(0.0, float(value)) class LoginBatchRunner: """批量登录执行器,通过进程级登录槽并发执行账号。""" def __init__( self, db: Session, account_ids: list[int], created_by: int, creator_permissions: list[str], max_login_retries: int = 0, max_total_time: float = 0, proxy_config: ProxyConfigModel | None = None, log_queue: asyncio.Queue | None = None, loop: asyncio.AbstractEventLoop | None = None, concurrency: int = 3, api_strategy: str = "wgapi", mode: str = "login", trigger_source: str = "manual", category: str = "", batch_id: str | None = None, log_sink: Callable[[dict[str, Any]], None] | None = None, ): self.db = db self.account_ids = account_ids self.created_by = created_by self.creator_permissions = creator_permissions # 限制最大重试次数,避免无限重试导致资源耗尽 # 0 表示使用默认值 20,其他值保持原样 self.max_login_retries = max_login_retries if max_login_retries > 0 else 20 self.max_total_time = max_total_time self.proxy_config = _snapshot_proxy_config(proxy_config) self.log_queue = log_queue self.loop = loop self.batch_id = (batch_id or uuid.uuid4().hex[:12])[:64] self.log_sink = log_sink self.concurrency = max( 1, min(concurrency, 10, login_concurrency_limit(db)), ) self.api_strategy = create_login_api_strategy(api_strategy) self.mode = mode if mode in ("login", "check", "relogin") else "login" # 显式分类覆盖(例如租约 CK 续期):留空时按 mode/trigger 自动判定。 self.category = str(category or "") self.trigger_source = ( trigger_source if trigger_source in { "manual", "automation", } else "manual" ) self._stop = threading.Event() self._counter_lock = threading.Lock() self._completed = 0 # 批次起点(单调时钟):每个账号开始执行前据此判断批次是否已超时。 self._batch_started_at = 0.0 # 逐账号日志走模块级 loguru sink(见文件头 _LOG_CONTEXT), # 这里保证 sink 与刷新线程都已就绪。 _install_task_log_sink() _start_task_log_flusher() # 共享代理获取器(无池,每次取新代理) self._proxy_runtime = build_proxy_runtime( self.proxy_config, stop_event=self._stop, ) self._shared_proxy_fetcher = self._proxy_runtime.api_fetcher def stop(self): self._stop.set() def _sleep_or_stop(self, seconds: float) -> bool: """可中断等待;返回 True 表示收到停止信号。""" deadline = time.monotonic() + seconds while time.monotonic() < deadline: if self._stop.is_set(): return True time.sleep(min(0.2, deadline - time.monotonic())) return self._stop.is_set() def _mark_relogin_stopped( self, task_id: int, message: str = "重新登录已停止,旧 Cookie 已保留", ) -> None: """把未开始或已中断的重登尝试收敛为终态,旧 CK 原封不动。""" worker_db = WorkerSessionLocal() try: task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first() if task and _attempt_in_flight(task): _mark_attempt_failed(task, message) # 停止也要留下原因:否则页面上只有一条「已停止」的状态, # 点开日志却什么都没有。 _append_persisted_log(task, "warning", message) worker_db.commit() finally: worker_db.close() def _mark_account_relogin_stopped( self, account_id: int, message: str = "重新登录已停止,旧 Cookie 已保留", ) -> None: """按**账号**收敛在途的重登尝试(新模型下调度单位是账号)。 与 `_mark_relogin_stopped` 的区别只是入口:批次挂了但记录还没建出来时, 这里是唯一能把「该账号的在途尝试」收干净的路径。 """ worker_db = WorkerSessionLocal() try: tasks = ( worker_db.query(LoginTask) .filter(LoginTask.account_id == account_id) .order_by(LoginTask.id.desc()) .all() ) changed = False for task in tasks: if _attempt_in_flight(task): _mark_attempt_failed(task, message) _append_persisted_log(task, "warning", message) changed = True if changed: worker_db.commit() finally: worker_db.close() def _record_skipped_attempt( self, task: LoginTask, account: AccountModel, reason: str, ) -> None: """记录一次「点了登录但没执行」的尝试。 以前配额/权限/在途判定失败时只写一条批次级 warning,**不建任务行**: 页面上账号凭空消失,运营既看不到原因也看不到日志,只能猜是不是 「登录预算」或者「账号限制」。现在给账号落一行 `skipped` 并在日志里 写明原因,和真正跑过的尝试在同一个列表里可见。 """ now = datetime.now(UTC) message = f"未执行:{reason}" task.attempt_status = "skipped" task.attempt_message = message task.attempt_batch_id = self.batch_id task.attempt_at = now task.finished_at = now # 账号已有 CK 时不动 status/message(沿用失败尝试的规则:旧 CK 的 # 成功语义不能被一次「没跑」覆盖)。 if not account.cookie: task.status = "skipped" task.message = message task.logs = [_task_log_entry("warning", f"本次登录未执行:{reason}")] def _record_batch_skipped(self, task_id: int, reason: str) -> None: """把本轮没轮到执行的账号记成「未执行」(不是失败)。""" worker_db = WorkerSessionLocal() try: task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first() if task is None: return now = datetime.now(UTC) message = f"未执行:{reason}" task.attempt_status = "skipped" task.attempt_message = message task.attempt_batch_id = self.batch_id task.attempt_at = now task.finished_at = now if not task.account.cookie: task.status = "skipped" task.message = message task.logs = [_task_log_entry("warning", f"本次登录未执行:{reason}")] worker_db.commit() finally: worker_db.close() def _push_log(self, level: str, message: str): # 逐账号日志由模块级 loguru sink 统一收集(含 core/ 的步骤日志); # 这里只负责 app.log、页面实时队列和外部 log_sink。 if message: log_level = ( level if level in {"debug", "info", "warning", "error", "success"} else "debug" ) getattr(logger, log_level)(f"[登录批次 {self.batch_id}] {message}") if self.log_queue and self.loop: asyncio.run_coroutine_threadsafe( self.log_queue.put({"level": level, "message": message}), self.loop, ) if self.log_sink is not None: try: self.log_sink({"level": level, "message": message}) except Exception: # noqa: BLE001 - 日志落库不能中断登录 logger.exception("写入登录批次持久日志失败: {}", self.batch_id) def _resolve_static_proxy(self) -> tuple[dict | None, str]: """解析静态代理配置。""" if not self.proxy_config or not self.proxy_config.enabled: return None, "" if self._proxy_runtime.static_proxies: proxy_url = ( self._proxy_runtime.static_proxies.get("https") or self._proxy_runtime.static_proxies.get("http") or "" ) return self._proxy_runtime.static_proxies, f"使用静态代理: {proxy_url}" # API代理:由 DouyuLogin 通过 proxy_fetcher 内部管理 return None, "" def _execute_one(self, task_id: int, acc_info: dict, total: int): """在独立线程中执行单个账号登录,使用独立的 DB 会话。""" # 日志上下文必须在**任何分支之前**建立:账号被停止跳过、任务行读不到、 # 代理配置异常这些路径以前直接 return,页面上连一行原因都看不到。 _LOG_CONTEXT.task_id = int(task_id or 0) _drop_task_logs(int(task_id or 0)) worker_db = None try: if self._stop.is_set(): self._push_log("warning", f"任务已停止,跳过: {acc_info['username']}") self._mark_relogin_stopped(task_id, "任务已停止,旧 Cookie 已保留") return # 批次在执行任务队列里占着一个槽。斗鱼邮箱验证码是攒批投递的,等一封 # 验证码最长 25 分钟/账号,批次不设上限的话 10 个账号能占着槽位跑近 # 一小时,把同队列的斗鱼履约批次饿死(新建任务直接报「斗鱼任务繁忙」)。 # 所以每个账号**开始执行前**都看一次批次时长,超时就不再接新账号。 budget = _batch_max_seconds() if budget > 0 and self._batch_started_at > 0: elapsed = time.monotonic() - self._batch_started_at if elapsed > budget: reason = ( f"批次已达 {int(budget)}s 时长上限,本轮未执行" "(该账号留待下一轮)" ) self._push_log("warning", reason) self._record_batch_skipped(task_id, reason) return worker_db = WorkerSessionLocal() task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first() if not task: return # CK、健康与重登状态都挂在账号上;登录记录只是一次尝试的历史。 account = task.account # 只推进尝试状态;账号持有的旧 CK 在成功前保持不变。 task.attempt_status = "running" task.attempt_message = ( "正在重新登录,旧 Cookie 保留中" if self.mode == "relogin" else "正在检测" if self.mode == "check" else "正在登录" ) worker_db.commit() with self._counter_lock: self._completed += 1 current = self._completed action_name = ( "检测" if self.mode == "check" else "重新登录" if self.mode == "relogin" else "登录" ) self._push_log( "info", f"[{current}/{total}] 开始{action_name}: {acc_info['username']}" ) try: # 代理配置也可能异常,必须由当前任务的失败处理收敛状态。 proxy_dict, proxy_msg = self._resolve_static_proxy() if proxy_msg: self._push_log("info", f"[{current}] {proxy_msg}") # 静态代理启用但配置为空 → 不可用 if ( self.proxy_config and self.proxy_config.enabled and not (self.proxy_config.http or self.proxy_config.https) and not self._shared_proxy_fetcher and not proxy_dict ): if self.mode == "relogin": _mark_attempt_failed( task, "重新登录失败: 代理不可用: 未配置代理(旧 Cookie 已保留)", ) else: _mark_attempt_failed( task, "代理不可用: 未配置代理", status="error" ) worker_db.commit() self._push_log( "error", f"[{current}] {acc_info['username']} 代理不可用" ) return # 只给登录器用的凭据快照。不能覆盖上面的 ORM `account`: # 重登成功后 `on_ck_verdict` 要写账号的 ck_check_*, # SimpleNamespace 没有这些字段,会把整次成功登录判成异常, # 新 Cookie 也就写不回去。 login_account = cast( AccountLike, SimpleNamespace( username=acc_info["username"], password=acc_info["password"], email=acc_info["email"], email_password=acc_info["email_password"], email_imap_server=acc_info["email_imap_server"] or "", email_imap_port=acc_info["email_imap_port"] or 993, email_imap_ssl=acc_info["email_imap_ssl"], ), ) loginer = DouyuLogin( login_account, proxy=proxy_dict, max_login_retries=self.max_login_retries, max_total_time=self.max_total_time, proxy_fetcher=self._shared_proxy_fetcher, stop_event=self._stop, api_strategy=self.api_strategy, ) result = ( loginer.check_account() if self.mode == "check" else loginer.login() ) if self.mode == "check" and result.success: status = ( result.code if result.code in CHECK_STATUS_MESSAGES else "account_auth_unknown" ) task.status = status # ⚠️ 行为变更(2026-10-04 CK 解耦):**检测不再清空账号的 CK**。 # 旧代码在这里写 `task.cookie = ""`,而那时记录的 cookie 就是账号的 # 唯一凭证 —— 于是一次「批量检测」就会把账号的登录态删掉。CK 换到账号 # 上之后,「检测账号凭据」与「CK 是否有效」本就是两件事(后者归 # ck_health 判),继续清空等于凭空制造不可逆的数据丢失 # (重登当前成功率极低,丢了补不回来)。 task.message = result.message or CHECK_STATUS_MESSAGES[status] # 检测结果本身就是这次尝试的结论,页面按 attempt_* 展示。 task.attempt_status = status task.attempt_message = task.message task.attempt_at = datetime.now(UTC) task.finished_at = datetime.now(UTC) level = CHECK_STATUS_LOG_LEVELS.get(status, "info") self._push_log( level, f"[{current}] {acc_info['username']} 检测结果: {task.message}", ) elif result.success: message = result.message or "登录成功" check_result = probe_session( result.cookie, checker=check_douyu_cookie, ) # 唯一替换旧 CK 的入口:登录成功后写回账号。 # # ⚠️ 必须传 **worker_db**(本线程的会话),不能传 self.db: # ① `self.db` 由主线程持有,SQLAlchemy Session 不是线程安全的; # ② 更致命的是 `emit()` 会往 account_events 插一行,其 # `account_id` 外键会对 accounts 那一行加**共享锁**。如果这 # 把锁加在**另一个**会话上,紧接着本会话对同一个账号的 # `UPDATE accounts SET cookie=...` 就会被自己人挡住 —— # 实测直接 50 秒后 `Lock wait timeout exceeded`,登录明明成功 # 却写不回 CK。事件本就该和状态变更在同一个事务里提交。 _write_login_success( worker_db, task, cookie=result.cookie, message=message, batch_id=self.batch_id, event_type=( EVENT_RELOGIN_OK if self.mode == "relogin" else EVENT_LOGIN_OK ), ) if account is not None: _persist_login_cookie_verification( worker_db, task, account, check_result, batch_id=self.batch_id, mode=self.mode, ) if account.ck_check_status == "valid": try: _enqueue_post_login_sync(worker_db, account) except Exception as exc: # noqa: BLE001 self._push_log( "warning", f"[{current}] 登录成功,但登记商品同步队列失败: {exc}", ) if account is not None and account.ck_check_status == "valid": self._push_log( "success", f"[{current}] {acc_info['username']} {task.message}", ) else: detail = ( account.ck_check_result.get("message") if account is not None and account.ck_check_result else "" ) self._push_log( "warning", f"[{current}] {acc_info['username']} {task.message or detail}", ) else: if self.mode == "relogin": # 重登失败不动旧 CK 与成功状态,只记录这次尝试失败 _mark_attempt_failed( task, f"重新登录失败: {result.message}(旧 Cookie 已保留)" ) self._push_log( "error", f"[{current}] {acc_info['username']} 重新登录失败: {result.message}", ) else: _mark_attempt_failed(task, result.message or "登录失败") self._push_log( "error", f"[{current}] {acc_info['username']} {action_name}失败: {result.message}", ) except Exception as e: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 if self.mode == "relogin": _mark_attempt_failed(task, f"重新登录异常: {e}(旧 Cookie 已保留)") self._push_log( "error", f"[{current}] {acc_info['username']} 重新登录异常: {e}" ) else: _mark_attempt_failed(task, str(e), status="error") self._push_log( "error", f"[{current}] {acc_info['username']} {action_name}异常: {e}", ) worker_db.commit() finally: _LOG_CONTEXT.task_id = 0 # 先关会话释放行锁,再用独立短事务写日志;反过来会在异常路径上 # 自己堵自己(同一行 UPDATE 等锁 50 秒)。 with _TASK_LOG_PERSIST_LOCK: logs = _drop_task_logs(task_id) if worker_db is not None: worker_db.close() _persist_task_logs(task_id, logs) def run(self): """在线程中执行批量登录。""" batch_id = self.batch_id concurrency = self.concurrency action_name = ( "账号检测" if self.mode == "check" else "重新登录" if self.mode == "relogin" else "登录" ) self._push_log( "info", f"批量{action_name}任务 {batch_id} 开始,共 {len(self.account_ids)} 个账号,并发数: {concurrency}", ) # 批次开始前同步一次出口 IP 到白名单,后续 fetch_new_proxy 不再主动同步 if self._shared_proxy_fetcher: ok, msg = self._shared_proxy_fetcher.warmup_whitelist() if msg != "无白名单凭据,跳过": self._push_log("info" if ok else "warning", f"白名单预热: {msg}") def _append_task_info(task: LoginTask, acc: AccountModel): # 只登记这次尝试:账号当前持有的 CK(status/cookie/message)在 # 登录成功前一律不动,批次被停止或失败都不会让账号失去 CK。 _begin_attempt( task, batch_id, "等待重新登录,旧 Cookie 已保留" if self.mode == "relogin" else "等待检测" if self.mode == "check" else "等待登录", ) self.db.flush() task_infos.append( { "task_id": task.id, "acc_info": { "username": acc.username, "password": acc.password, "email": acc.email, "email_password": acc.email_password, "email_imap_server": acc.email_imap_server or "", "email_imap_port": acc.email_imap_port or 993, "email_imap_ssl": acc.email_imap_ssl if acc.email_imap_ssl is not None else True, }, } ) try: # 创建或复用任务记录(顺序执行,线程安全) # # **重登模式也从 account_ids 走**(2026-10-04 CK 解耦):以前重登传的是 # 「持有 CK 的记录 id」,因为 CK 挂在记录上;现在 CK 在账号上,调度单位就是 # 账号,登录记录只是「这次尝试」的历史 —— 顺带让**没有登录历史的账号** # 也能被重登(以前它根本进不了候选)。 task_infos: list[dict] = [] # {task_id, acc_info} seen_account_ids = set() for aid in self.account_ids: if aid in seen_account_ids: continue seen_account_ids.add(aid) acc = ( self.db.query(AccountModel) .filter(AccountModel.id == aid) .with_for_update() .first() ) if not acc: continue # 权限检查:客服只能跑分配给自己的 if ( "login:view_all" not in self.creator_permissions and acc.assigned_to != self.created_by ): self._push_log("warning", f"跳过无权账号: {acc.username}") continue # 解耦后不再需要「哪一行持有 CK」这个不变量(CK 在账号上)。 # 这里只需要保证**同一账号不并发两行**: # ① 复用该账号在途的尝试(避免并发两个批次各建一行); # ② 否则复用最近一条失败/中断的历史,避免刷屏; # ③ 都没有就新建一行(历史而已,允许一个账号多行)。 # # 先找行、再做配额判定:被配额挡下的账号也要有行可落日志, # 否则页面上「点了登录什么都没发生」。 task = ( self.db.query(LoginTask) .filter( LoginTask.account_id == aid, or_( func.coalesce(LoginTask.attempt_status, "").in_( LOGIN_ATTEMPT_IN_FLIGHT_STATUSES ), and_( LoginTask.attempt_status == "", LoginTask.status.in_(LOGIN_ATTEMPT_IN_FLIGHT_STATUSES), ), ), ) .order_by(LoginTask.id.desc()) .first() ) if task is None: # 复用最近一条**失败/中断/跳过**的历史,避免每次失败都刷一行。 # 注意要同时看 attempt_status:账号有 CK 时 `_mark_attempt_failed` # 刻意不动 status(保护旧语义),所以失败记录的 status 可能还停在 # pending —— 只看 status 就永远命不中,行数会无限长。 task = ( self.db.query(LoginTask) .filter( LoginTask.account_id == aid, or_( LoginTask.status.in_(["failed", "error", "skipped"]), LoginTask.attempt_status.in_( ["failed", "error", "skipped"] ), ), ) .order_by(LoginTask.id.desc()) .first() ) if task is None: task = LoginTask( batch_id=batch_id, account_id=aid, status="pending", created_by=self.created_by, ) self.db.add(task) quota = reserve_login_attempt( self.db, account=acc, mode=self.mode, trigger_source=self.trigger_source, batch_id=batch_id, created_by=self.created_by, category=self.category, ) if not quota.allowed: self._push_log( "warning", f"跳过账号 {acc.username}: {quota.reason}", ) if quota.reason == "该账号已有登录任务在执行": # 另一个批次正在跑这个账号:别碰它的行,它的日志由 # 正在执行的那次尝试负责。 continue self._record_skipped_attempt(task, acc, quota.reason) continue _append_task_info(task, acc) self.db.commit() total = len(task_infos) if total == 0: self._push_log("warning", "没有可执行的账号") self._push_log("result", "") return # 全局登录槽负责并发;批次只提交任务并收集结果。 futures = [] # 批次起点:每个账号**开始执行前**都要看它,超时就不再接新账号。 self._batch_started_at = time.monotonic() for item_index, item in enumerate(task_infos): if self._stop.is_set(): self._push_log("warning", "任务已停止,跳过剩余账号") for pending_item in task_infos[item_index:]: self._mark_relogin_stopped( pending_item["task_id"], "任务已停止,旧 Cookie 已保留" ) break future = submit( TaskLane.LOGIN, self._execute_one, item["task_id"], item["acc_info"], total, stopped=self._stop.is_set, ) if future is None: break futures.append(future) for future in as_completed(futures): try: future.result() except Exception as e: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 self._push_log("error", f"Worker 异常: {e}") self._push_log("info", f"批量{action_name}任务 {batch_id} 完成") self._push_log("result", "") finally: try: _settle_login_attempts(batch_id) except Exception as exc: # noqa: BLE001 logger.exception(f"[登录批次 {batch_id}] 结算登录尝试流水失败: {exc}") # 标记批次结束:WS 端据此决定何时清理注册表(断线重连可继续订阅日志)。 batch_registry.mark_finished(batch_id) # 确保 DB Session 被关闭,避免连接泄漏 self.db.close() class BatchRegistry: """管理运行中的登录批次状态。""" def __init__(self): self._batches: dict[str, dict] = {} def register( self, batch_id: str, log_queue: asyncio.Queue | None, loop: asyncio.AbstractEventLoop | None, runner: LoginBatchRunner, owner_id: int | None = None, ): self._batches[batch_id] = { "log_queue": log_queue, "loop": loop, "runner": runner, "owner_id": owner_id, "finished": False, "finished_at": None, } def get(self, batch_id: str): return self._batches.get(batch_id) def mark_finished(self, batch_id: str): """标记批次已结束(幂等;不在本注册表的批次为无操作)。 与虎牙批次一致:WS 端只在 finished 后 pop,客户端断线重连仍可订阅 到运行中批次的实时日志。 """ batch = self._batches.get(batch_id) if batch: batch["finished"] = True batch["finished_at"] = time.time() def pop(self, batch_id: str): return self._batches.pop(batch_id, None) def _settle_login_attempts(batch_id: str) -> None: """用新的短事务把本批不可变登录流水结转到终态。""" session = WorkerSessionLocal() try: attempts = ( session.query(LoginAttempt) .filter( LoginAttempt.batch_id == batch_id, LoginAttempt.status.in_(("pending", "running")), ) .all() ) for attempt in attempts: task = ( session.query(LoginTask) .filter( LoginTask.account_id == attempt.account_id, LoginTask.attempt_batch_id == batch_id, ) .order_by(LoginTask.id.desc()) .first() ) task_status = (task.attempt_status if task else "") or ( task.status if task else "" ) message = (task.attempt_message if task else "") or ( task.message if task else "" ) if task_status == "success" or task_status == "account_verified": status = "success" failure_kind = "" elif task_status in CHECK_STATUS_MESSAGES: status = "failed" failure_kind = ( "network" if task_status == "account_auth_unknown" else "credential" ) elif task_status in {"failed", "error"}: status = task_status failure_kind = classify_failure(message) else: status = "failed" failure_kind = "interrupted" finish_login_attempt( session, attempt, status=status, failure_kind=failure_kind, ) session.commit() finally: session.close() # 模块级单例 batch_registry = BatchRegistry() def _converge_interrupted_attempts(db: Session, message: str) -> int: """把遗留的在途尝试收敛为失败。 只写 attempt_*;对已经没有 CK 的记录才顺带落一个失败终态。返回收敛条数。 """ tasks = ( db.query(LoginTask) .filter( or_( LoginTask.attempt_status.in_(ATTEMPT_IN_FLIGHT_STATUSES), LoginTask.status.in_(_LEGACY_IN_FLIGHT_STATUSES), ) ) .all() ) cleaned = 0 for task in tasks: if not _attempt_in_flight(task): continue _mark_attempt_failed(task, message) # 进程重启会把这些尝试永远留在「进行中」;只改状态不留日志, # 页面恢复后就只剩一条失败状态,看不出是被重启打断的。 _append_persisted_log(task, "warning", message) cleaned += 1 if cleaned: db.commit() return cleaned def cleanup_orphan_relogin_tasks( db: Session, message: str = "重新登录已中断(服务重启),旧 Cookie 已保留", ) -> int: """服务重启后收敛遗留的重登尝试,旧 CK 原封不动。""" return _converge_interrupted_attempts(db, message) def cleanup_orphan_login_tasks( db: Session, message: str = "登录已中断(服务重启),旧 Cookie 已保留", ) -> int: """服务重启后收敛遗留的登录尝试。 在途尝试只体现在 attempt_* 上,收敛它不会碰到账号已有的 CK;只有本来 就没有 CK 的记录才会顺带标记失败,避免页面永久显示「排队中」。 """ return _converge_interrupted_attempts(db, message) # 在模块末尾导入 WorkerSessionLocal(避免循环导入) from ..database import WorkerSessionLocal