fix(douyu): 替换 CK 是最后一步,只有登录成功才写回记录

上一版把可见性改成「记录里还有 CK」,账号不会再消失,但根因还在:批次启动
时就把复用的成功记录改成 pending(旧 CK 仍在),停止或失败后没人恢复状态,
记录一直显示成一次没完成的登录。

按「替换 CK 是最后一步」把两者拆开:

- login_tasks 新增 attempt_status / attempt_message / attempt_batch_id /
  attempt_at,批次只写 attempt_*,status/cookie/message 只在登录成功时更新;
- _begin_attempt 只登记尝试,_mark_attempt_failed 只记录失败(已有 CK 的记录
  原样不动),_write_login_success 是唯一替换旧 CK 的入口;
- 停止批次、代理不可用、登录异常、进程重启清理全部改为收敛 attempt_*,
  因此停止一个批次不可能再让账号失去 CK;
- 复用的记录改用「持有 CK 的记录」,不再创建第二条记录,失败记录在无 CK 时
  才复用;
- 登录任务列表/统计按 attempt_* 展示「这次登录怎么样了」,批次筛选同时匹配
  attempt_batch_id;CK 操作页的重登状态也从 attempt_* 映射;
- 迁移 20261001_0035 归一存量数据:持有 CK 的记录 status 统一为 success、
  历史状态搬进 attempt_*,无 CK 且卡在 pending/running 的收敛为 failed。

新增测试:批次失败/停止不碰旧 CK、成功后替换 CK、列表展示尝试状态、
迁移存量数据归一。
This commit is contained in:
yml2213
2026-10-01 18:29:49 +08:00
parent 64c399617a
commit 6a25097412
10 changed files with 808 additions and 153 deletions
+11 -11
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import uuid
from datetime import UTC, datetime
from sqlalchemy import and_, select
from sqlalchemy import and_, func, select
from sqlalchemy.orm import Session
from core.douyu.activity_client import DouyuActivityClient
@@ -181,18 +181,16 @@ def ensure_douyu_config(db: Session) -> DouyuConfig:
return config
# 登录/重登批次正在处理的状态:这些记录已被批次接管,不允许并发操作。
LOGIN_IN_FLIGHT_STATUSES = ("pending", "running", "relogin_pending", "relogin_running")
# 登录/重登尝试的在途状态:判断只看 attempt_*,与记录持有的 CK 无关。
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = ("pending", "running")
def cookie_holding_filter():
"""判定登录记录当前是否仍持有 Cookie。
账号是否有 CK 只取决于记录里是否还留着 Cookie,而不是取决于批次状态:
普通登录在排队时会把复用的成功记录临时置为 ``pending``/``running``,
CK 重登失败会置为 ``relogin_failed``,这些状态都按设计保留旧 Cookie
(见 ``login_service`` 的「旧 Cookie 已保留」分支),账号必须继续可见。
只有 Cookie 真正被清空(账号检测成功)时才不再算持有 CK。
账号是否有 CK 只取决于记录里是否还留着 Cookie。登录尝试(attempt_*)
在成功前不会碰 status/cookie/message,所以停止、失败、进程重启都不会
让账号失去 CK;只有 Cookie 真正被清空(账号检测成功)时才不再持有。
"""
return and_(
LoginTask.cookie.isnot(None),
@@ -216,12 +214,14 @@ def latest_cookie_login_task(db: Session, account_id: int) -> LoginTask | None:
def cookie_operable_filter():
"""判定登录记录能否基于现有 Cookie 再做检测或重登。
正在被登录/重登批次处理的行(pending/running/relogin_*)已由批次接管,
并发再点检测或重登只会互相覆盖状态,因此排除在外。
正在被批次处理的记录(attempt_* 处于在途状态)已由批次接管,并发再点
检测或重登只会互相覆盖,因此排除在外;CK 与 status 不参与判断。
"""
return and_(
cookie_holding_filter(),
LoginTask.status.notin_(LOGIN_IN_FLIGHT_STATUSES),
func.coalesce(LoginTask.attempt_status, "").notin_(
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
),
)
+176 -111
View File
@@ -11,6 +11,7 @@ from types import SimpleNamespace
from typing import cast
from loguru import logger
from sqlalchemy import or_
from sqlalchemy.orm import Session
from core.douyu import DouyuLogin, IframeLoginAPI, WgapiLoginAPI
@@ -21,6 +22,7 @@ from ..models import Account as AccountModel
from ..models import LoginTask
from ..models import ProxyConfig as ProxyConfigModel
from .cookie_check_service import check_douyu_cookie
from .douyu_service import cookie_holding_filter
def _create_api_strategy(strategy_name: str):
@@ -89,6 +91,66 @@ def _snapshot_proxy_config(
)
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 的记录保持原样。"""
completed_at = datetime.now(UTC)
task.attempt_status = status if status in {"failed", "error"} else "failed"
task.attempt_message = message
task.attempt_at = completed_at
if not task.cookie:
# 还没有任何 CK 需要保护:保持旧的失败语义,便于复用记录与页面统计。
task.status = task.attempt_status
task.message = message
task.finished_at = completed_at
def _write_login_success(
task: LoginTask, *, cookie: str, message: str, batch_id: str
) -> None:
"""登录成功后把新 CK 写回记录:这是唯一替换旧 CK 的入口。"""
completed_at = datetime.now(UTC)
task.status = "success"
task.cookie = cookie
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
class LoginBatchRunner:
"""批量登录执行器,在线程中运行,通过 ThreadPoolExecutor 并发登录多个账号。"""
@@ -175,14 +237,12 @@ class LoginBatchRunner:
task_id: int,
message: str = "重新登录已停止,旧 Cookie 已保留",
) -> None:
"""将未开始或已中断的重登任务收敛为保留旧 CK 的终态。"""
"""把未开始或已中断的重登尝试收敛为终态,旧 CK 原封不动。"""
worker_db = SessionLocal()
try:
task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first()
if task and task.status in ("relogin_pending", "relogin_running"):
task.status = "relogin_failed"
task.message = message
task.finished_at = datetime.now(UTC)
if task and _attempt_in_flight(task):
_mark_attempt_failed(task, message)
worker_db.commit()
finally:
worker_db.close()
@@ -219,8 +279,7 @@ class LoginBatchRunner:
"""在独立线程中执行单个账号登录,使用独立的 DB 会话。"""
if self._stop.is_set():
self._push_log("warning", f"任务已停止,跳过: {acc_info['username']}")
if self.mode == "relogin":
self._mark_relogin_stopped(task_id)
self._mark_relogin_stopped(task_id, "任务已停止,旧 Cookie 已保留")
return
worker_db = SessionLocal()
@@ -229,11 +288,15 @@ class LoginBatchRunner:
if not task:
return
if self.mode == "relogin":
task.status = "relogin_running"
task.message = "正在重新登录,旧 Cookie 保留中"
else:
task.status = "running"
# 只推进尝试状态;记录持有的旧 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:
@@ -266,14 +329,14 @@ class LoginBatchRunner:
and not proxy_dict
):
if self.mode == "relogin":
task.status = "relogin_failed"
task.message = (
"重新登录失败: 代理不可用: 未配置代理(旧 Cookie 已保留)"
_mark_attempt_failed(
task,
"重新登录失败: 代理不可用: 未配置代理(旧 Cookie 已保留)",
)
else:
task.status = "error"
task.message = "代理不可用: 未配置代理"
task.finished_at = datetime.now(UTC)
_mark_attempt_failed(
task, "代理不可用: 未配置代理", status="error"
)
worker_db.commit()
self._push_log(
"error", f"[{current}] {acc_info['username']} 代理不可用"
@@ -315,15 +378,18 @@ class LoginBatchRunner:
task.status = status
task.cookie = ""
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:
task.status = "success"
task.cookie = result.cookie
task.message = result.message or "登录成功"
message = result.message or "登录成功"
if self.mode == "relogin":
check_result = check_douyu_cookie(result.cookie)
task.ck_check_status = (
@@ -337,16 +403,26 @@ class LoginBatchRunner:
}
task.ck_checked_at = check_result["checked_at"]
if check_result["valid"]:
task.message = "重新登录成功,Cookie 有效"
message = "重新登录成功,Cookie 有效"
else:
message = f"重新登录成功,但 Cookie 有效性检测失败: {check_result['message']}"
# 唯一替换旧 CK 的入口:登录成功后写回新 CK。
_write_login_success(
task,
cookie=result.cookie,
message=message,
batch_id=self.batch_id,
)
if self.mode == "relogin":
if task.ck_check_status == "valid":
self._push_log(
"success",
f"[{current}] {acc_info['username']} 重新登录成功,Cookie 已替换并验证有效",
)
else:
task.message = f"重新登录成功,但 Cookie 有效性检测失败: {check_result['message']}"
self._push_log(
"warning",
f"[{current}] {acc_info['username']} 重新登录成功,但 Cookie 有效性检测失败: {check_result['message']}",
f"[{current}] {acc_info['username']} 重新登录成功,但 Cookie 有效性检测失败: {task.ck_check_result.get('message') if task.ck_check_result else ''}",
)
else:
self._push_log(
@@ -355,18 +431,16 @@ class LoginBatchRunner:
)
else:
if self.mode == "relogin":
# 重新登录失败时保留旧 Cookie 与成功状态,仅记录失败原因,行不消失
task.status = "relogin_failed"
task.message = (
f"重新登录失败: {result.message}(旧 Cookie 已保留)"
# 重登失败不动旧 CK 与成功状态,只记录这次尝试失败
_mark_attempt_failed(
task, f"重新登录失败: {result.message}(旧 Cookie 已保留)"
)
self._push_log(
"error",
f"[{current}] {acc_info['username']} 重新登录失败: {result.message}",
)
else:
task.status = "failed"
task.message = result.message
_mark_attempt_failed(task, result.message or "登录失败")
self._push_log(
"error",
f"[{current}] {acc_info['username']} {action_name}失败: {result.message}",
@@ -374,20 +448,17 @@ class LoginBatchRunner:
except Exception as e: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
if self.mode == "relogin":
task.status = "relogin_failed"
task.message = f"重新登录异常: {e}(旧 Cookie 已保留)"
_mark_attempt_failed(task, f"重新登录异常: {e}(旧 Cookie 已保留)")
self._push_log(
"error", f"[{current}] {acc_info['username']} 重新登录异常: {e}"
)
else:
task.status = "error"
task.message = str(e)
_mark_attempt_failed(task, str(e), status="error")
self._push_log(
"error",
f"[{current}] {acc_info['username']} {action_name}异常: {e}",
)
task.finished_at = datetime.now(UTC)
worker_db.commit()
finally:
@@ -416,15 +487,17 @@ class LoginBatchRunner:
self._push_log("info" if ok else "warning", f"白名单预热: {msg}")
def _append_task_info(task: LoginTask, acc: AccountModel):
task.batch_id = batch_id
if self.mode == "relogin":
# 旧 Cookie 仅在 result.success 后由 _execute_one 原子替换。
task.status = "relogin_pending"
task.message = "等待重新登录,旧 Cookie 已保留"
else:
task.status = "pending"
task.message = ""
task.finished_at = None
# 只登记这次尝试:账号当前持有的 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(
{
@@ -491,50 +564,40 @@ class LoginBatchRunner:
self._push_log("warning", f"跳过无权账号: {acc.username}")
continue
# 一个斗鱼账号只保留一条成功 CK:再次普通登录时更新最新成功记录。
latest_success_task = (
# 一个斗鱼账号只保留一条持有 CK 的记录:优先复用它,
# 登录成功后才把新 CK 写回同一条记录。
task = (
self.db.query(LoginTask)
.filter(
LoginTask.account_id == aid, LoginTask.status == "success"
LoginTask.account_id == aid,
cookie_holding_filter(),
)
.order_by(LoginTask.finished_at.desc(), LoginTask.id.desc())
.order_by(LoginTask.id.desc())
.first()
)
if latest_success_task:
duplicate_success_tasks = (
self.db.query(LoginTask)
.filter(
LoginTask.account_id == aid,
LoginTask.status == "success",
LoginTask.id != latest_success_task.id,
)
.all()
)
for duplicate_task in duplicate_success_tasks:
self.db.delete(duplicate_task)
task = latest_success_task
else:
# 复用该账号最近一条失败任务记录,避免重复产生多条失败历史。
existing_task = (
if task is None:
# 复用最近一条失败记录,避免重复产生多条失败历史。
task = (
self.db.query(LoginTask)
.filter(
LoginTask.account_id == aid,
LoginTask.status.in_(["failed", "error"]),
or_(
LoginTask.cookie.is_(None),
LoginTask.cookie == "",
),
)
.order_by(LoginTask.id.desc())
.first()
)
if existing_task:
existing_task.cookie = ""
task = existing_task
else:
task = LoginTask(
batch_id=batch_id,
account_id=aid,
status="pending",
created_by=self.created_by,
)
self.db.add(task)
if task is None:
task = LoginTask(
batch_id=batch_id,
account_id=aid,
status="pending",
created_by=self.created_by,
)
self.db.add(task)
_append_task_info(task, acc)
@@ -551,9 +614,12 @@ class LoginBatchRunner:
for item_index, item in enumerate(task_infos):
if self._stop.is_set():
self._push_log("warning", "任务已停止,跳过剩余账号")
if self.mode == "relogin":
for pending_item in task_infos[item_index:]:
self._mark_relogin_stopped(pending_item["task_id"])
# 所有模式都要把没轮到的尝试收敛掉,否则会一直停在
# 「等待中」;已有 CK 的记录本身不受影响。
for pending_item in task_infos[item_index:]:
self._mark_relogin_stopped(
pending_item["task_id"], "任务已停止,旧 Cookie 已保留"
)
break
future = executor.submit(
self._execute_one,
@@ -624,51 +690,50 @@ class BatchRegistry:
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)
cleaned += 1
if cleaned:
db.commit()
return cleaned
def cleanup_orphan_relogin_tasks(
db: Session,
message: str = "重新登录已中断(服务重启),旧 Cookie 已保留",
) -> int:
"""服务重启后收敛遗留重登状态,避免页面永久显示重登中。"""
tasks = (
db.query(LoginTask)
.filter(LoginTask.status.in_(("relogin_pending", "relogin_running")))
.all()
)
if not tasks:
return 0
finished_at = datetime.now(UTC)
for task in tasks:
task.status = "relogin_failed"
task.message = message
task.finished_at = finished_at
db.commit()
return len(tasks)
"""服务重启后收敛遗留的重登尝试,旧 CK 原封不动。"""
return _converge_interrupted_attempts(db, message)
def cleanup_orphan_login_tasks(
db: Session,
message: str = "登录已中断(服务重启),旧 Cookie 已保留",
) -> int:
"""服务重启后收敛遗留的普通登录状态。
"""服务重启后收敛遗留的登录尝试。
普通登录批次停止或进程重启时,未轮到的记录会永远停在 pending/running,
页面上一直显示「排队中」,旧 CK 也失去终态说明。统一收敛为 failed 并
保留 Cookie,账号仍然可见可重登。
在途尝试只体现在 attempt_* 上,收敛它不会碰到账号已有的 CK;只有本来
就没有 CK 的记录才会顺带标记失败,避免页面永久显示「排队中」。
"""
tasks = (
db.query(LoginTask).filter(LoginTask.status.in_(("pending", "running"))).all()
)
if not tasks:
return 0
finished_at = datetime.now(UTC)
for task in tasks:
task.status = "failed"
task.message = message
task.finished_at = finished_at
db.commit()
return len(tasks)
return _converge_interrupted_attempts(db, message)
# 在模块末尾导入 SessionLocal(避免循环导入)