S1 加好了列,本提交把**读与写一起切**过去。这是设计里「同一份数据的读与写必须
在同一个提交里切」的要求:先切读或先切写都会出现「写账号、读记录」的中间态,
跑起来不报错,只是默默用错数据。
## 核心改动
**判定「谁有 CK」不再借道登录记录**
- `cookie_holding_filter()` / `cookie_operable_filter()` / `cookie_holding_account_ids_query()`
/ `visible_douyu_task_accounts()` 全部改为作用于 `Account`;
- `cookie_operable_filter()` 的「在途排除」仍查 `login_tasks`(那是**某次尝试**的属性),
用 `NOT EXISTS` 子查询 + 迁移 0042 新增的 `(account_id, attempt_status)` 索引;
- 删除死代码 `latest_cookie_login_task()`;`latest_cookie()` 改为直接读账号。
**CK 写入**
- `_write_login_success()` 写 `Account.cookie / cookie_updated_at / cookie_source`;
- `_mark_attempt_failed()` 改看**账号**有没有 CK(决定是否沿用旧的失败语义);
- 检测模式的 `task.cookie = ""` **不再清空账号的 CK**(见下「行为变更」)。
**自动化作业按账号调度**
- `ck_health`:`_select_tasks` → `_select_accounts`,`db.query(Account)`;新增
`count_remaining()`(刻意不带 LIMIT,否则积压数恒等于批次上限);
- `ck_relogin`:同样按账号选行;结算改为「账号 + 本轮尝试记录」,
退避进度写账号;`settle_fresh_results(batch_id)` 按 `attempt_batch_id` 配对,
`run_ck_relogin` 把 **account_ids** 交给 runner;
- 顺带让**没有任何登录历史的账号**也能被巡检/重登(以前它们永远进不了队列)。
**登录批次**
- `LoginBatchRunner` 去掉 `relogin_task_ids`,重登与登录统一走 `account_ids`;
- 批次行复用逻辑重写:只保证「同一账号不并发两行」,不再关心「哪一行持有 CK」。
失败行复用同时看 `attempt_status`(账号有 CK 时 `_mark_attempt_failed` 刻意不动
`status`,只看 status 会永远命不中 → 每次失败刷一行)。
**删除护栏语义变更(用户可感知)**
- 去掉「持有 CK 的记录不可删」——CK 在账号上,删历史不再影响登录态,历史终于可清理;
- **保留**「在途尝试不可删」(批次线程正拿着那条记录)。
## 行为变更(需评审)
1. **账号检测不再清空 CK**。旧代码在 check 模式写 `task.cookie = ""`,而那时记录的
cookie 就是账号唯一凭证 —— 一次「批量检测」会把账号登录态删掉。解耦后
「检测账号凭据」与「CK 是否有效」本就是两件事(后者归 `ck_health` 判),
继续清空等于凭空制造不可逆的数据丢失(重登当前成功率极低)。
2. **Cookie 页的记录单位从「登录记录」变成「账号」**,所有接口的 id 入参/出参
变成 `account_id`;`DELETE /cookies/{id}` 清的是该账号的 CK,**必写审计**。
3. 重复检测从「同一账号多行持 CK」改为「**同一个 CK 出现在多个账号上**」——
后者才是真风险(两个账号共用一个登录态)。用 sha256 指纹分组:
CK 是 AES-GCM + 随机 nonce 加密,**同一明文每次密文都不同**,比密文永远比不出重复。
## 修掉一个真实并发缺陷
`_write_login_success` 原先被传入 `self.db`(runner 主会话),而它是在**工作线程**里
用 `worker_db` 执行的。`emit()` 会往 `account_events` 插一行,其 `account_id` 外键对
`accounts` 那一行加**共享锁**;这把锁加在另一个会话上,紧接着本会话的
`UPDATE accounts SET cookie=...` 就被自己人挡住 —— 实测 **50 秒后
`Lock wait timeout exceeded`,登录明明成功却写不回 CK**(改造前 UPDATE 打在
`login_tasks` 上所以没撞上)。改为传 `worker_db`:事件本就该和状态变更同事务提交,
顺带修掉跨线程共用一个 Session 的隐患。
## 验证
- 全量 pytest **368 passed / 6 skipped**;迁移链 3 passed;
- 前端 `tsc -b && vite build` 通过;
- `ruff check` / `ruff format --check` 全绿(顺带修掉 main 上遗留的 F821);
- 新增/改写的关键回归:**删掉全部登录历史后账号的 CK 与健康状态仍在**、
**无登录历史的账号也能进巡检队列**、结算不碰 CK、删除护栏改为在途语义。
仍未做(设计里排期的后续阶段):`account_lifecycle` 状态收口(S3)、事件发射点补齐(S4)、
业务事实直发事件(S5)、账号页重构(S6)。注意 `status` 目前只有模型默认值与迁移回填,
所以 `disabled/archived` 还没有任何写入方——S3 落地时要把自动化选行的状态过滤一起补上。
375 lines
14 KiB
Python
375 lines
14 KiB
Python
"""CK 自动重登作业(P1b)。
|
||
|
||
和巡检(P1a)是一对:巡检只产出「谁失效了」的清单,本作业负责把能救的救回来。
|
||
线上实测(2026-10-02)20 个失效账号重登 **20/20 成功** —— 失效是会话级过期,
|
||
不是凭证问题。
|
||
|
||
**核心设计:失败必须分型。** 线上数据表明 415 个重登失败里只有 35% 是真正需要
|
||
人工的(极验滑块),另外 64%(取码失败 + 重启中断)其实可自动重试;不分型就会
|
||
把可救名额一起推给人工。分型结果落 ``login_tasks.relogin_failure_kind``。
|
||
|
||
本作业**默认关闭**,且按规划 §7.4.7 分三段上线(小规模实测已完成 → 限量 → 全量)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import random
|
||
from datetime import UTC, datetime, timedelta
|
||
from typing import Any
|
||
|
||
from sqlalchemy import func, or_
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ....database import SessionLocal
|
||
from ....models import Account, AutomationJob, LoginTask, User
|
||
from ....models import ProxyConfig as ProxyConfigModel
|
||
from ...account_events_service import EVENT_RELOGIN_FAILED, emit
|
||
from ...douyu_service import cookie_holding_filter, cookie_operable_filter
|
||
from ...login_service import LoginBatchRunner, get_relogin_limits
|
||
|
||
JOB_KEY = "ck_relogin"
|
||
|
||
# 失败分型 → 后续动作。
|
||
# 需要人工的:极验滑块(自动重试只会加重风控)、凭证问题(重试多少次都一样)。
|
||
MANUAL_KINDS = frozenset({"captcha", "credential"})
|
||
# 可自动重试的:取码失败/超时(多为邮件延迟)、中断(服务重启或人工停止)、
|
||
# 网络异常。email_quota 单列,因为它要退避到次日而不是按小时退避。
|
||
RETRYABLE_KINDS = frozenset({"email_code", "interrupted", "network"})
|
||
|
||
# 退避阶梯(分钟):1h → 3h → 12h → 24h,超出取最后一级。
|
||
BACKOFF_MINUTES = (60, 180, 720, 1440)
|
||
|
||
# 自动重登时给 runner 的总时长上限。默认的 600 秒会长时间占住调度线程,
|
||
# 自动化场景压到 240 秒:一轮跑不完的账号留着下一轮(它们本来就有退避)。
|
||
AUTO_MAX_TOTAL_TIME = 240
|
||
|
||
# 邮箱配额打满后退避到次日零点,再叠加随机抖动,避免整点齐发。
|
||
QUOTA_JITTER_MINUTES = 30
|
||
|
||
|
||
def classify_failure(message: str | None) -> str:
|
||
"""把重登失败消息映射成分型(见规划 §7.4.3)。
|
||
|
||
顺序很重要:「邮箱验证码发送次数已达上限」既含「验证码」也含「上限」,
|
||
必须先在 ``email_quota`` 命中,否则会被归到可重试的 ``email_code`` 上,
|
||
导致次日才该重试的账号被按小时反复撞配额。
|
||
"""
|
||
text = message or ""
|
||
if "上限" in text or "配额" in text:
|
||
return "email_quota"
|
||
if "极验" in text or "验证" in text and "滑块" in text:
|
||
return "captcha"
|
||
if "验证码" in text:
|
||
return "email_code"
|
||
if "中断" in text or "已停止" in text or "任务已停止" in text:
|
||
return "interrupted"
|
||
if "密码" in text or "账号不存在" in text or "缺少密码或邮箱" in text:
|
||
return "credential"
|
||
# 请求失败/超时/连接异常,以及未知文案:都按可重试处理。
|
||
# 宁可多给一次机会(有每日上限兜底),也不要把可能只是抖动的账号推给人工。
|
||
return "network"
|
||
|
||
|
||
def _cutoff(now: datetime) -> datetime:
|
||
return now
|
||
|
||
|
||
def build_select_query(
|
||
db: Session,
|
||
job: AutomationJob,
|
||
now: datetime,
|
||
*,
|
||
max_attempts: int = 2,
|
||
system_user_id: int | None = None,
|
||
):
|
||
"""构造本轮重登候选的查询(与取行分开,便于按方言编译做回归)。
|
||
|
||
解耦后**按账号选行**(2026-10-04):CK 与 ``ck_check_status`` / ``relogin_*``
|
||
都在 ``accounts`` 上。以前是 ``db.query(LoginTask).join(Account)`` —— 那样
|
||
「没有登录历史的账号」永远进不了重登队列,而重登本来只关心账号。
|
||
|
||
「在途尝试」仍然要查 ``login_tasks``(那是某次尝试的属性),由
|
||
``cookie_operable_filter`` 的 NOT EXISTS 子查询完成,走迁移 0042 新增的
|
||
``(account_id, attempt_status)`` 索引。
|
||
"""
|
||
query = (
|
||
db.query(Account)
|
||
.filter(Account.ck_check_status == "invalid")
|
||
.filter(cookie_operable_filter())
|
||
.filter(Account.auto_managed.is_(True))
|
||
.filter(Account.relogin_attempts < max_attempts)
|
||
.filter(
|
||
or_(
|
||
Account.relogin_next_at.is_(None),
|
||
Account.relogin_next_at <= _cutoff(now),
|
||
)
|
||
)
|
||
)
|
||
# 已判定需要人工的类型不再自动重试(极验/凭证)。空值用 coalesce 兜住历史值。
|
||
query = query.filter(
|
||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||
tuple(sorted(MANUAL_KINDS))
|
||
)
|
||
)
|
||
if system_user_id is not None:
|
||
pass # 预留:将来若需要限制到某个归属人,在这里加过滤
|
||
return query.order_by(
|
||
Account.relogin_next_at.is_(None).desc(),
|
||
Account.relogin_next_at.asc(),
|
||
Account.id.asc(),
|
||
).limit(max(int(job.batch_size or 0), 1))
|
||
|
||
|
||
def _load_batch_state(
|
||
session: Session, batch_id: str
|
||
) -> tuple[dict[int, tuple[Account, LoginTask]], list[int]]:
|
||
"""读回某一批次产生的尝试记录,并配对其所属账号。
|
||
|
||
按 ``attempt_batch_id`` 找 —— ``_begin_attempt`` 会给每一条被本批次接管的记录
|
||
打上批次号。所以即使记录是**复用**的旧行,也能被准确对应回本轮。
|
||
"""
|
||
tasks = (
|
||
session.query(LoginTask)
|
||
.filter(LoginTask.attempt_batch_id == batch_id)
|
||
.order_by(LoginTask.id.asc())
|
||
.all()
|
||
)
|
||
state: dict[int, tuple[Account, LoginTask]] = {}
|
||
order: list[int] = []
|
||
for task in tasks:
|
||
account = session.get(Account, task.account_id)
|
||
if account is None:
|
||
continue
|
||
state[account.id] = (account, task)
|
||
order.append(account.id)
|
||
return state, order
|
||
|
||
|
||
def settle_fresh_results(
|
||
batch_id: str, *, now: datetime, max_attempts: int = 2
|
||
) -> dict[str, int]:
|
||
"""在**新会话(新事务)**里读回批次结果并结算。
|
||
|
||
必须新开会话,不能复用调度器传进来的 ``db``:那个会话在挑候选时就已经开了
|
||
事务,而 MySQL 默认隔离级别是 **REPEATABLE READ** —— 在同一事务里重新查询
|
||
只会看到事务开始时的快照,看不到 runner 在另一个会话里提交的成功结果。
|
||
|
||
线上为此踩过一次:10 条重登**实际全部成功**,结算却按失败写回,给它们加了
|
||
退避时间,其中 2 条还被标成「极验」进了待人工队列。SQLite 的读一致性与 MySQL
|
||
不同,这类问题在 SQLite 上复现不出来。
|
||
"""
|
||
session = SessionLocal()
|
||
try:
|
||
fresh, order = _load_batch_state(session, batch_id)
|
||
counters = settle_results(
|
||
session,
|
||
fresh,
|
||
order,
|
||
now=now,
|
||
max_attempts=max_attempts,
|
||
)
|
||
session.commit()
|
||
return counters
|
||
finally:
|
||
session.close()
|
||
|
||
|
||
def count_pending_relogin(db: Session, *, max_attempts: int = 2) -> int:
|
||
"""待自动重登的**积压**条数(给页面显示用)。
|
||
|
||
刻意不复用 ``build_select_query``:那个查询带 ``LIMIT batch_size``,用它取
|
||
count 只会得到批次上限(页面上显示恒等于 10),完全看不出积压。这里也**不
|
||
按退避窗口过滤** —— 退避是「什么时候试」的细节,不影响「还有多少要处理」。
|
||
"""
|
||
return int(
|
||
db.query(func.count(Account.id))
|
||
.filter(Account.ck_check_status == "invalid")
|
||
.filter(cookie_holding_filter())
|
||
.filter(Account.auto_managed.is_(True))
|
||
.filter(Account.relogin_attempts < max_attempts)
|
||
.filter(
|
||
func.coalesce(Account.relogin_failure_kind, "").notin_(
|
||
tuple(sorted(MANUAL_KINDS))
|
||
)
|
||
)
|
||
.scalar()
|
||
or 0
|
||
)
|
||
|
||
|
||
def _system_user_id(db: Session) -> int | None:
|
||
"""自动重登要用一个真实用户身份落 ``created_by``(外键非空,且便于追责)。
|
||
|
||
取最早创建的超管作为「系统操作人」;库是空的就返回 None,作业会跳过本轮。
|
||
"""
|
||
row = (
|
||
db.query(User.id)
|
||
.filter(User.role == "super_admin")
|
||
.order_by(User.id.asc())
|
||
.first()
|
||
)
|
||
if row:
|
||
return int(row[0])
|
||
row = db.query(User.id).order_by(User.id.asc()).first()
|
||
return int(row[0]) if row else None
|
||
|
||
|
||
def _next_retry_at(kind: str, attempts: int, now: datetime) -> datetime:
|
||
if kind == "email_quota":
|
||
tomorrow = (now + timedelta(days=1)).replace(
|
||
hour=0, minute=0, second=0, microsecond=0
|
||
)
|
||
return tomorrow + timedelta(minutes=random.uniform(0, QUOTA_JITTER_MINUTES))
|
||
step = BACKOFF_MINUTES[min(max(attempts, 1), len(BACKOFF_MINUTES)) - 1]
|
||
return now + timedelta(minutes=step)
|
||
|
||
|
||
def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||
now = datetime.now(UTC)
|
||
config = job.config or {}
|
||
max_attempts = int(config.get("max_attempts_per_day", 2) or 2)
|
||
|
||
system_user_id = _system_user_id(db)
|
||
if system_user_id is None:
|
||
return {
|
||
"scanned": 0,
|
||
"valid": 0,
|
||
"invalid": 0,
|
||
"skipped": 0,
|
||
"message": "库里没有可用用户,无法以系统身份发起重登",
|
||
}
|
||
|
||
accounts = build_select_query(db, job, now, max_attempts=max_attempts).all()
|
||
if not accounts:
|
||
return {"scanned": 0, "valid": 0, "invalid": 0, "skipped": 0}
|
||
|
||
# 调度单位是**账号**(CK 在账号上);登录记录只是这次尝试的历史。
|
||
account_ids = [account.id for account in accounts]
|
||
proxy = db.query(ProxyConfigModel).first()
|
||
_, max_total_time = get_relogin_limits()
|
||
|
||
# 批次用独立会话(runner 会在自己的线程/会话里写库),跑完再回来读结果。
|
||
runner_db = SessionLocal()
|
||
runner = LoginBatchRunner(
|
||
db=runner_db,
|
||
account_ids=account_ids,
|
||
created_by=system_user_id,
|
||
# 自动化要对全库生效,不受「只能操作分配给自己的账号」限制。
|
||
creator_permissions=["login:view_all", "cookie:operate"],
|
||
max_login_retries=int(config.get("max_login_retries", 5) or 5),
|
||
max_total_time=min(int(max_total_time), AUTO_MAX_TOTAL_TIME),
|
||
proxy_config=proxy,
|
||
log_queue=None,
|
||
loop=None,
|
||
concurrency=max(min(int(job.concurrency or 3), 8), 1),
|
||
mode="relogin",
|
||
)
|
||
batch_id = runner.batch_id
|
||
try:
|
||
runner.run()
|
||
finally:
|
||
runner_db.close()
|
||
|
||
# runner 在另一个会话里提交了结果:必须用新事务读回(见 settle_fresh_results)。
|
||
counters = settle_fresh_results(batch_id, now=now, max_attempts=max_attempts)
|
||
|
||
parts = [
|
||
f"本轮重登 {counters['scanned']} 条",
|
||
f"成功 {counters['valid']}",
|
||
f"失败 {counters['invalid']}",
|
||
]
|
||
if counters["retry"]:
|
||
parts.append(f"待重试 {counters['retry']}")
|
||
if counters["email_quota"]:
|
||
parts.append(f"其中配额满 {counters['email_quota']}(退避到次日)")
|
||
if counters["manual"]:
|
||
parts.append(f"转人工 {counters['manual']}")
|
||
return {
|
||
"scanned": counters["scanned"],
|
||
"valid": counters["valid"],
|
||
"invalid": counters["invalid"],
|
||
"relogin_started": counters["scanned"],
|
||
"relogin_success": counters["valid"],
|
||
"skipped": 0,
|
||
"message": ",".join(parts),
|
||
"detail": {
|
||
"batch_id": batch_id,
|
||
"manual": counters["manual"],
|
||
"retry": counters["retry"],
|
||
"email_quota": counters["email_quota"],
|
||
},
|
||
}
|
||
|
||
|
||
def settle_results(
|
||
db: Session,
|
||
fresh: dict[int, tuple[Account, LoginTask]],
|
||
account_ids: list[int],
|
||
*,
|
||
now: datetime,
|
||
max_attempts: int = 2,
|
||
) -> dict[str, int]:
|
||
"""批次跑完后结算:成功的清零,失败的按分型决定重试还是转人工。
|
||
|
||
解耦后 **决策看「账号 + 本轮的尝试记录」**(2026-10-04):
|
||
- 成败来自这次尝试(``LoginTask.attempt_status``);
|
||
- 退避进度写在**账号**上(``Account.relogin_*``)—— 它是账号的状态,
|
||
不该随某条历史记录一起被删掉。
|
||
|
||
单独抽出来是因为这段是 P1b 的核心决策逻辑,必须能脱离真实登录做单测。
|
||
只改 ``relogin_*`` 四个字段,**不碰 CK 本体**(CK 由 runner 在成功时替换)。
|
||
|
||
``db`` 用于写账号事件(转人工时记一条);事件是旁路,写失败不影响结算。
|
||
"""
|
||
counters = {
|
||
"scanned": len(account_ids),
|
||
"valid": 0,
|
||
"invalid": 0,
|
||
"manual": 0,
|
||
"retry": 0,
|
||
"email_quota": 0,
|
||
}
|
||
for account_id in account_ids:
|
||
entry = fresh.get(account_id)
|
||
if entry is None:
|
||
continue
|
||
account, task = entry
|
||
if task.attempt_status == "success":
|
||
counters["valid"] += 1
|
||
account.relogin_attempts = 0
|
||
account.relogin_next_at = None
|
||
account.relogin_failure_kind = ""
|
||
account.relogin_last_error = ""
|
||
continue
|
||
|
||
counters["invalid"] += 1
|
||
kind = classify_failure(task.attempt_message)
|
||
account.relogin_failure_kind = kind
|
||
account.relogin_last_error = (task.attempt_message or "")[:500]
|
||
account.relogin_attempts = int(account.relogin_attempts or 0) + 1
|
||
if kind in MANUAL_KINDS or account.relogin_attempts >= max_attempts:
|
||
# 转人工:极验/凭证问题重试无意义,次数用尽也不该无限撞。
|
||
counters["manual"] += 1
|
||
account.relogin_next_at = None
|
||
# 只在「转人工」时记事件:还要退避重试的不记,否则同一账号每轮都刷一条。
|
||
emit(
|
||
db,
|
||
account_id=account.id,
|
||
event_type=EVENT_RELOGIN_FAILED,
|
||
title=f"自动重登转人工({kind})",
|
||
occurred_at=now,
|
||
detail={
|
||
"kind": kind,
|
||
"attempts": account.relogin_attempts,
|
||
"error": (task.attempt_message or "")[:200],
|
||
},
|
||
source="login",
|
||
source_ref=f"relogin_failed:{task.id}:{int(now.timestamp())}",
|
||
)
|
||
continue
|
||
if kind == "email_quota":
|
||
counters["email_quota"] += 1
|
||
counters["retry"] += 1
|
||
account.relogin_next_at = _next_retry_at(kind, account.relogin_attempts, now)
|
||
return counters
|