Files
live-hub-py/web/backend/services/automation/jobs/ck_health.py
T
yml2213 0a922ce56d feat(account): S4 事件发射点补齐 —— 审计与时间线打通、批量事件、ck_invalid 只认转变
S3 让 `status` 可信,S4 让**时间线完整**:账号上发生的事,时间线里都能查到。

## 补齐「定义了却从没发过」的事件

`assigned` / `tag_changed` 这两个类型早就定义了、前端 `EVENT_STYLE` 也渲染了,
但**全仓没有任何代码发过**(`grep` 只有定义处)。本次接上:

- 单个分配 / 批量分配 → `assigned`(detail 带 assigned_to / assigned_username)
- 单个改标签 / 批量改标签 / 按筛选批量改标签 → `tag_changed`(detail 带 from/to)

## 新增 `ck_cleared`,并修掉 `ck_invalid` 的刷屏

- **`ck_cleared`**:清 CK 是**不可逆**操作(重登当前成功率极低),时间线里却不留痕。
  现在单个清除与批量清除共用 `account_lifecycle.on_ck_cleared()`。
- **`ck_invalid` 改为只在「由好变坏」时发**。旧实现每轮巡检只要判定 invalid 就发一条,
  源码注释写着「避免每轮刷屏」,**但代码并没有做到** —— 6 小时一轮、失效一周就是
  28 条一模一样的事件。判定失效是**一次状态转变**,不是每轮读数。`error`(查不到)
  同样不改变结论、不发事件。

## 审计与时间线一次写完(防漏一边)

新增 `audit_service.record_account_action()`:**审计 + 账号事件一起写**,并把
`account_id` 落到审计上。这两件事必须成对出现 —— 只写审计,时间线就缺「谁改了什么」;
只发事件,合规审计就缺一条。分成两次调用写,迟早有人漏一边(`assigned` 就是这么漏的)。

顺带把批量删除的审计补上被删账号 id(`detail.account_ids`,截前 200 条):
删账号会**连带删掉它的事件时间线**(外键),审计是唯一痕迹 —— 这正是 10-03
那次事故要留的东西。

## 批量操作不再逐条开 SAVEPOINT

批量分配/改标签可能覆盖几千个账号,而每个账号的时间线都该各留一条。
逐条走 `emit()` 会给每条开一个 SAVEPOINT,几千条时请求明显变慢。
新增 `emit_bulk()`:一次 executemany,整批包在**一个** SAVEPOINT 里,
与 `emit()` 一样**绝不抛异常**(整批失败就整批丢弃 + warning,不影响业务写入)。

## 检测入口收口:4 处 → 1 个 `on_ck_verdict()`

`ck_health` / 人工检测 / 工作台执行前检测 / 重登后复检 原本各自写
`ck_check_status` + `ck_check_result` + `ck_checked_at` + 发事件 + 调 `sync_status`,
口径容易分叉(`ck_invalid` 的刷屏就是这么来的)。现在统一走
`account_lifecycle.on_ck_verdict()`,顺序固定:**写结论 → 由好变坏记事件 → 重算状态**。

至此 `account_lifecycle` 成为**唯一**写生命周期字段的模块,并加了一条**源码扫描用例**
把它钉死(任何地方直接 `acc.status = ...` 都会让它红,并指出 file:line)——
比写在文档里的约定可靠。虎牙的 `huya_accounts.status` 是同一个病,但属另一套模型,
已在用例里显式排除并注明。

## 接口与前端

- 时间线支持 `?category=` 筛选(lifecycle / auth / business / ops);
  响应补 `category` / `subject_*` / `actor_*`
- 前端 `EVENT_STYLE` 补上 `status_changed`(**S3 我漏的**:加了事件类型却没加样式,
  页面上显示成原始英文)与 `ck_cleared`;时间线加「分类」筛选

## 验证

- `TZ=Asia/Shanghai`:**420 passed / 6 skipped**(S3 后 404 → 新增 16 条)
- 迁移链 3 passed;ruff check/format 全绿;前端 `tsc -b && vite build` 与
  `npm run lint`(0 errors)均通过
- **两条关键用例都做过「反向验证」**(先注入旧行为确认会红):
  - 把 `ck_invalid` 改回「每轮都发」→ 用例报 `3 == 1`;
  - 在路由里直接写 `acc.status = ...` → 不变量用例给出精确 file:line。
- 新用例还覆盖:批量分配/改标签逐账号发事件、清 CK 事件与审计关联、
  `emit_bulk` 的跳过与容错、时间线分类筛选、批量删除的 id 留痕。

未做(后续):S5 业务事实直发事件 + `douyu_tasks` 保留策略、S6 账号页重构 +
`bind_status` 三列拆解。`remark_changed` 目前没有改备注的接口,故无发射点(已在文档标注)。
2026-10-04 15:09:46 +08:00

198 lines
7.4 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.
"""CK 巡检作业(P1a)。
只做一件事:把「持有 CK 但久未检测」的账号挑出来,调现成的
``check_douyu_cookie()`` 检测,把结果写回 ``ck_check_*``。
**本作业不修改 CK 本身**:不写 ``cookie`` / ``status`` / ``message``,也不碰
``attempt_*``。P1a 上线后人工照旧可以点检测和重登,自动重登是 P1b 的事。
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import or_
from sqlalchemy.orm import Session
from ....models import Account, AutomationJob
from ...account_lifecycle import MANUAL_STATES, on_ck_verdict
from ...cookie_check_service import check_douyu_cookie
from ...douyu_service import cookie_operable_filter
JOB_KEY = "ck_health"
FLUSH_EVERY = 25
# 斗鱼明确表示「这个 CK 不能用」的说法。只有命中这些才算真的失效。
AUTH_FAILURE_MARKERS = (
"登陆异常",
"登录异常",
"未登录",
"登陆失效",
"登录失效",
"重新登陆",
"重新登录",
"账户登陆",
)
# 非鉴权类失败(网络超时、响应异常、被判风控)占比超过它就自动暂停作业。
# 这类失败说明「我们查不到」,不是「这个 CK 失效了」;如果不加区分地写
# invalid,斗鱼接口抖动一小时就能把上千个好账号标成失效,客服会误判成
# CK 大面积挂掉。
ERROR_PAUSE_RATIO = 0.3
ERROR_PAUSE_MIN_SCANNED = 20
def classify_result(result: dict[str, Any]) -> str:
"""把检测结果分成三类:valid / invalid(真失效)/ error(查不到)。
- ``valid``:斗鱼两个接口都通过;
- ``invalid``:斗鱼明确回复「未登录 / 登陆异常」之类的鉴权失败;
- ``error``:其余失败(请求失败、超时、响应异常、未知结构)——
**不能当成失效**,也不覆盖该行原来的结论。
"""
if result.get("valid"):
return "valid"
message = str(result.get("message") or "")
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
return "invalid"
return "error"
def _candidates_query(db: Session, job: AutomationJob, now: datetime):
"""本轮「待检测账号」的完整候选集(**不带 LIMIT**,供计数复用)。
口径与人工点检测一致(``cookie_operable_filter``:账号有 CK 且没有在途尝试),
再加三条:距上次检测超过作业间隔、账号允许自动管理、**未被停用/归档**。
排序刻意不用 ``NULLS FIRST``:那是 PostgreSQL/SQLite 语法,**MySQL 会报
1064 语法错误**(生产踩过一次)。改用 ``ck_checked_at IS NULL DESC``,
三个方言下语义一致且都是合法 SQL。
"""
cutoff = now - timedelta(seconds=max(int(job.interval_seconds or 0), 60))
return (
db.query(Account)
.filter(cookie_operable_filter())
.filter(Account.auto_managed.is_(True))
# 生命周期状态机:停用/归档的账号不参与任何自动化(见 account_lifecycle)。
.filter(Account.status.notin_(MANUAL_STATES))
.filter(
or_(
Account.ck_checked_at.is_(None),
Account.ck_checked_at < cutoff,
)
)
.order_by(
Account.ck_checked_at.is_(None).desc(),
Account.ck_checked_at.asc(),
Account.id.asc(),
)
)
def build_select_query(db: Session, job: AutomationJob, now: datetime):
"""构造本轮要检测**账号**的查询(与取行分开,便于按方言编译做回归)。
解耦后**按账号选行**(2026-10-04):CK 与 ``ck_check_*`` 都在 ``accounts`` 上,
以前是 ``db.query(LoginTask).join(Account)`` —— 那样「没有登录历史的账号」
永远进不了巡检队列,而且一个账号有多行时会被重复检测。
"""
return _candidates_query(db, job, now).limit(max(int(job.batch_size or 0), 1))
def _select_accounts(db: Session, job: AutomationJob, now: datetime) -> list[Account]:
return build_select_query(db, job, now).all()
def count_remaining(db: Session, job: AutomationJob, now: datetime) -> int:
"""剩余待检账号数(给页面提示用)。
刻意**不用** ``build_select_query`` —— 那个带 ``LIMIT batch_size``,
取 count 只会得到批次上限,完全看不出积压。
"""
return int(
_candidates_query(db, job, now).order_by(None).with_entities(Account.id).count()
or 0
)
def _detect(account: Account) -> dict[str, Any]:
try:
return check_douyu_cookie(account.cookie or "")
except Exception as exc: # noqa: BLE001 单个账号失败不影响整轮
return {
"valid": False,
"message": f"检测异常: {exc}",
"fish_ball": None,
"nickname": None,
"level": None,
"checked_at": datetime.now(UTC),
}
def run_ck_health(db: Session, job: AutomationJob) -> dict[str, Any]:
now = datetime.now(UTC)
accounts = _select_accounts(db, job, now)
if not accounts:
return {"scanned": 0, "valid": 0, "invalid": 0, "skipped": 0}
results: dict[int, dict[str, Any]] = {}
concurrency = max(min(int(job.concurrency or 1), 16), 1)
with ThreadPoolExecutor(max_workers=concurrency) as pool:
futures = {pool.submit(_detect, account): account for account in accounts}
for future in as_completed(futures):
account = futures[future]
results[account.id] = future.result()
# 只写检测结果三件套;cookie / status / attempt_* 一律不动。
valid = invalid = errors = 0
for index, account in enumerate(accounts, start=1):
result = results.get(account.id)
if result is None:
continue
verdict = classify_result(result)
if verdict == "valid":
valid += 1
elif verdict == "invalid":
invalid += 1
else:
errors += 1
# 结论落定 = 写 ck_check_* + 由好变坏时记事件 + 重算生命周期状态。
# 三件事的**顺序与口径**收在 `on_ck_verdict` 里,四个检测入口共用。
on_ck_verdict(db, account, verdict, detail=result, occurred_at=now)
if index % FLUSH_EVERY == 0:
db.commit()
db.commit()
# 剩余待检数量只用于提示,不参与调度。
remaining = count_remaining(db, job, now)
error_ratio = errors / len(accounts) if accounts else 0.0
paused = False
if errors >= ERROR_PAUSE_MIN_SCANNED and error_ratio > ERROR_PAUSE_RATIO:
# 大面积「查不到」通常是斗鱼接口抖动或被风控,继续跑只会污染更多账号。
job.enabled = False
job.updated_at = datetime.now(UTC)
paused = True
message = f"本轮检测 {len(accounts)} 条,剩余待检 {remaining} 条"
if errors:
message += f";非鉴权类失败 {errors} 条({error_ratio:.0%})"
if paused:
message += ";失败占比过高,已自动暂停作业"
return {
"scanned": len(accounts),
"valid": valid,
"invalid": invalid,
"skipped": errors,
"message": message,
"detail": {
"remaining": remaining,
"concurrency": concurrency,
"errors": errors,
"error_ratio": round(error_ratio, 4),
"paused": paused,
},
}