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` 目前没有改备注的接口,故无发射点(已在文档标注)。
331 lines
13 KiB
Python
331 lines
13 KiB
Python
"""账号事件流:写入与查询。
|
||
|
||
## 定位
|
||
|
||
`accounts` 存**当前状态**(积分、余额、开通标记),这张表存**发生过什么**。
|
||
账号详情页 = 状态卡(读 `accounts`)+ 时间线(读本表)。
|
||
|
||
## 两条写入路径
|
||
|
||
1. **直接发射**(`emit`):CK 失效/登录成功/重登、精英宝典与电竞手册开通 —— 这些
|
||
只在内存里出现过,不记就永远没有;
|
||
2. **增量收集**(`automation/jobs/account_events_collect.py`):充值/兑换/积分到账/绑定 ——
|
||
这些已经是 `douyu_tasks` 的行,由收集器按水位线往后提取,不动 runner 代码。
|
||
本模块只提供 `_task_to_event` 映射给它用。
|
||
|
||
## 两条硬约束
|
||
|
||
- **发射是旁路**:`emit` 任何失败都不能影响登录/兑换主流程(内部吞异常 + 记日志,
|
||
并用 SAVEPOINT 隔离,避免污染调用方的事务);
|
||
- **幂等**:`source_ref` 唯一键兜住「收集器重跑」「事件重复发射」。没有它,重跑一次
|
||
时间线就多一份重复记录。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from datetime import UTC, datetime
|
||
from typing import Any
|
||
|
||
from loguru import logger
|
||
from sqlalchemy import text
|
||
from sqlalchemy.orm import Session
|
||
|
||
# ── 事件类型 ──────────────────────────────────────────────
|
||
# 命名保持「名词_状态」风格,便于前端归类与筛选。
|
||
EVENT_IMPORTED = "imported" # 账号导入(读 accounts.created_at,一般不落表)
|
||
EVENT_LOGIN_OK = "login_ok" # 登录成功(含新 CK)
|
||
EVENT_CK_INVALID = "ck_invalid" # CK 判定失效
|
||
EVENT_CK_CLEARED = "ck_cleared" # CK 被清除(人工清除 / 账号删除前的清理)
|
||
EVENT_RELOGIN_OK = "relogin_ok" # 自动重登成功
|
||
EVENT_RELOGIN_FAILED = "relogin_failed" # 自动重登失败(转人工/退避)
|
||
EVENT_BIND_OK = "bind_ok" # 绑定/换绑
|
||
EVENT_RECHARGE = "recharge" # 充值到账
|
||
EVENT_EXCHANGE = "exchange" # 兑换(含消耗积分)
|
||
EVENT_POINTS_CREDIT = "points_credit" # 积分到账(含到期时间)
|
||
EVENT_ELITE_OPENED = "elite_opened" # 精英宝典开通
|
||
EVENT_ESPORTS_OPENED = "esports_opened" # 电竞手册开通
|
||
EVENT_ASSIGNED = "assigned" # 分配客服
|
||
EVENT_TAG_CHANGED = "tag_changed" # 标签变更
|
||
EVENT_STATUS_CHANGED = "status_changed" # 生命周期状态变迁(停用/归档/失效…)
|
||
|
||
# 有符号金额的事件类型(用于页面「累计充值/累计消耗」):
|
||
# 充值为正、兑换为负,其余不计入金额统计。
|
||
INCOME_TYPES = (EVENT_RECHARGE,)
|
||
OUTCOME_TYPES = (EVENT_EXCHANGE,)
|
||
|
||
# 粗分类:决定时间线怎么分组、以及哪些事件算「业务台账」。
|
||
CATEGORY_LIFECYCLE = "lifecycle" # 生命周期状态变迁
|
||
CATEGORY_AUTH = "auth" # 登录与 CK
|
||
CATEGORY_BUSINESS = "business" # 充值 / 兑换 / 积分 / 开通
|
||
CATEGORY_OPS = "ops" # 人工操作(分配 / 标签 / 停用)
|
||
|
||
|
||
def to_naive_utc(value: datetime) -> datetime:
|
||
"""把时间归一成 **naive UTC**(本服务所有时间列的落库形态)。
|
||
|
||
约定与 `database.UTCDateTime` 一致,也是全仓通行写法:
|
||
|
||
- **naive → 视为「已经是 UTC」,原样使用**;
|
||
- aware → 换算到 UTC 后去掉 tzinfo。
|
||
|
||
⚠️ 绝对不能直接写 `value.astimezone(UTC)`:对 naive 值,Python 会把它当作
|
||
**服务器本地时间**再换算。本机 UTC+8 时事件时间会被整整扣掉 8 小时,
|
||
而 naive 值的来源很常见 —— 用**裸 SQL** 读 DATETIME 列(如收集器读
|
||
`douyu_tasks.finished_at`)拿到的就是 naive,因为它绕过了 `UTCDateTime`
|
||
装饰器。仓库里 `scheduler._as_utc` / `yyb_service._as_utc` / `audit.py`
|
||
都遵守了这条约定,本函数与它们同口径。
|
||
"""
|
||
if value.tzinfo is None:
|
||
return value
|
||
return value.astimezone(UTC).replace(tzinfo=None)
|
||
|
||
|
||
def _now() -> datetime:
|
||
return datetime.now(UTC)
|
||
|
||
|
||
_INSERT_SQL = text(
|
||
"""
|
||
INSERT INTO account_events (
|
||
account_id, event_type, category, occurred_at, title,
|
||
amount, balance_after, subject_type, subject_key,
|
||
detail, source, actor_type, actor_id, source_ref, created_at
|
||
) VALUES (
|
||
:account_id, :event_type, :category, :occurred_at, :title,
|
||
:amount, :balance_after, :subject_type, :subject_key,
|
||
:detail, :source, :actor_type, :actor_id, :source_ref, :created_at
|
||
)
|
||
"""
|
||
)
|
||
|
||
|
||
def _event_params(
|
||
*,
|
||
account_id: int,
|
||
event_type: str,
|
||
title: str,
|
||
occurred_at: datetime | None = None,
|
||
amount: int | None = None,
|
||
balance_after: int | None = None,
|
||
detail: dict[str, Any] | None = None,
|
||
source: str = "manual",
|
||
source_ref: str | None = None,
|
||
category: str = "",
|
||
subject_type: str = "",
|
||
subject_key: str = "",
|
||
actor_type: str = "",
|
||
actor_id: int | None = None,
|
||
) -> dict[str, Any]:
|
||
"""把一次调用归一成落库参数(`emit` 与 `emit_bulk` 共用,避免 SQL 写两遍)。"""
|
||
return {
|
||
"account_id": account_id,
|
||
"event_type": event_type,
|
||
"category": (category or "")[:16],
|
||
"occurred_at": to_naive_utc(occurred_at or _now()),
|
||
"title": (title or "")[:256],
|
||
"amount": amount,
|
||
"balance_after": balance_after,
|
||
"subject_type": (subject_type or "")[:16],
|
||
"subject_key": (subject_key or "")[:96],
|
||
"detail": json.dumps(detail, ensure_ascii=False, default=str)
|
||
if detail
|
||
else None,
|
||
"source": source[:24],
|
||
"actor_type": (actor_type or "")[:16],
|
||
"actor_id": actor_id,
|
||
"source_ref": (source_ref or None),
|
||
"created_at": to_naive_utc(_now()),
|
||
}
|
||
|
||
|
||
def emit(
|
||
db: Session,
|
||
*,
|
||
account_id: int,
|
||
event_type: str,
|
||
title: str,
|
||
occurred_at: datetime | None = None,
|
||
amount: int | None = None,
|
||
balance_after: int | None = None,
|
||
detail: dict[str, Any] | None = None,
|
||
source: str = "manual",
|
||
source_ref: str | None = None,
|
||
category: str = "",
|
||
subject_type: str = "",
|
||
subject_key: str = "",
|
||
actor_type: str = "",
|
||
actor_id: int | None = None,
|
||
) -> bool:
|
||
"""记录一条账号事件。返回是否真的写入(幂等命中/异常时为 False)。
|
||
|
||
**绝不抛异常**:事件是旁路,不能因为记不上一条时间线就让登录或兑换失败。
|
||
用 SAVEPOINT 包住,失败只回滚这一条,不影响调用方已经做过的事。
|
||
|
||
`occurred_at` 是**业务发生时间**,可以是 aware,也可以是 naive
|
||
(naive 按约定视为已是 UTC,见 `to_naive_utc`)。
|
||
|
||
`category` / `subject_*` / `actor_*` 支撑台账检索:
|
||
例如「该账号该商品最近一次兑换」走
|
||
`(account_id, event_type, subject_key, occurred_at)` 复合索引。
|
||
"""
|
||
if not account_id or not event_type:
|
||
return False
|
||
|
||
params = _event_params(
|
||
account_id=account_id,
|
||
event_type=event_type,
|
||
title=title,
|
||
occurred_at=occurred_at,
|
||
amount=amount,
|
||
balance_after=balance_after,
|
||
detail=detail,
|
||
source=source,
|
||
source_ref=source_ref,
|
||
category=category,
|
||
subject_type=subject_type,
|
||
subject_key=subject_key,
|
||
actor_type=actor_type,
|
||
actor_id=actor_id,
|
||
)
|
||
|
||
try:
|
||
# SAVEPOINT:即使这条插入失败(例如 source_ref 撞唯一键),
|
||
# 也只回滚它自己,调用方事务里已完成的写入不受影响。
|
||
with db.begin_nested():
|
||
db.execute(_INSERT_SQL, params)
|
||
return True
|
||
except Exception as exc: # noqa: BLE001 - 旁路,任何失败都不上抛
|
||
logger.warning(f"写入账号事件失败(account={account_id} {event_type}):{exc}")
|
||
return False
|
||
|
||
|
||
def emit_bulk(db: Session, events: list[dict[str, Any]]) -> int:
|
||
"""一次写多条事件,返回实际写入条数。
|
||
|
||
用于**批量账号操作**(批量分配 / 批量改标签):一次操作可能覆盖几千个账号,
|
||
每个账号的时间线都该各留一条「谁在什么时候改了什么」。逐条走 `emit()` 会给
|
||
每条开一个 SAVEPOINT,几千条时请求明显变慢 —— 这里改成一次 executemany,
|
||
整批包在**一个** SAVEPOINT 里。
|
||
|
||
与 `emit()` 一样**绝不抛异常**:整批失败就整批丢弃(记 warning),
|
||
不会污染调用方的事务,也不会让「批量分配」因为记不上时间线而失败。
|
||
|
||
每个 dict 的键与 `emit()` 的关键字参数同名(`account_id` / `event_type` /
|
||
`title` 必填)。
|
||
"""
|
||
rows = [
|
||
_event_params(**{**item, "occurred_at": item.get("occurred_at")})
|
||
for item in events
|
||
if item.get("account_id") and item.get("event_type")
|
||
]
|
||
if not rows:
|
||
return 0
|
||
|
||
try:
|
||
with db.begin_nested():
|
||
db.execute(_INSERT_SQL, rows)
|
||
return len(rows)
|
||
except Exception as exc: # noqa: BLE001 - 旁路,任何失败都不上抛
|
||
logger.warning(f"批量写入账号事件失败({len(rows)} 条):{exc}")
|
||
return 0
|
||
|
||
|
||
# ── douyu_tasks 增量收集 ──────────────────────────────────
|
||
# 只收集「业务事件」,例行轮询(query_*)一律不进时间线 —— 它们在 douyu_tasks 里
|
||
# 占绝大多数(query_limited_goods 就 6.7 万行),收进去时间线没法看。
|
||
COLLECTED_TASK_TYPES = (
|
||
"exchange_goods",
|
||
"create_gold_qr",
|
||
"donate_elite_gift",
|
||
"confirm_bind",
|
||
"confirm_esports_bind",
|
||
)
|
||
|
||
|
||
def _task_to_event(task_type: str, result: Any) -> dict[str, Any] | None:
|
||
"""把一条 douyu_tasks 行转成事件参数;解析不出返回 None(跳过并告警)。
|
||
|
||
⚠️ 字段路径是**抽样实测**得到的(见设计文档 §4.2),不是猜的。
|
||
解析不出时必须跳过而不是抛出去 —— 一行坏数据不能卡住整条水位线。
|
||
"""
|
||
if isinstance(result, str):
|
||
try:
|
||
result = json.loads(result)
|
||
except ValueError:
|
||
return None
|
||
if not isinstance(result, dict):
|
||
return None
|
||
|
||
if task_type == "exchange_goods":
|
||
name = result.get("commodity_name") or "兑换"
|
||
score = result.get("score")
|
||
points_after = (result.get("points_query") or {}).get("points")
|
||
return {
|
||
"event_type": EVENT_EXCHANGE,
|
||
"title": f"兑换 {name}",
|
||
"amount": -int(score) if isinstance(score, (int, float)) else None,
|
||
"balance_after": points_after if isinstance(points_after, int) else None,
|
||
"detail": {
|
||
"commodity_name": name,
|
||
"commodity_id": result.get("commodity_id"),
|
||
"order_id": result.get("order_id"),
|
||
"exchange_id": result.get("exchange_id"),
|
||
"game_name": result.get("game_name"),
|
||
"game_channel": result.get("game_channel"),
|
||
"score": score,
|
||
},
|
||
}
|
||
|
||
if task_type == "create_gold_qr":
|
||
amount = result.get("buy_num") or result.get("pay_amount")
|
||
supplier = result.get("supplier_order") or {}
|
||
try:
|
||
amount_int = int(float(amount)) if amount is not None else None
|
||
except (TypeError, ValueError):
|
||
amount_int = None
|
||
return {
|
||
"event_type": EVENT_RECHARGE,
|
||
"title": f"充值 {amount_int if amount_int is not None else ''}".strip(),
|
||
"amount": amount_int,
|
||
"balance_after": None,
|
||
"detail": {
|
||
"order_id": result.get("order_id"),
|
||
"supplier_order_id": supplier.get("order_id"),
|
||
"supplier_finished_at": supplier.get("finish_time"),
|
||
"channel": result.get("recharge_channel"),
|
||
"douyu_uid": result.get("douyu_uid"),
|
||
},
|
||
}
|
||
|
||
if task_type == "donate_elite_gift":
|
||
gain = result.get("gift_points_expected_gain")
|
||
points = result.get("points")
|
||
will_expire = ((result.get("points_query") or {}).get("raw") or {}).get("data")
|
||
expire_at = (
|
||
will_expire.get("willExpireTime") if isinstance(will_expire, dict) else None
|
||
)
|
||
return {
|
||
"event_type": EVENT_POINTS_CREDIT,
|
||
"title": f"积分到账 +{gain}" if gain is not None else "积分到账",
|
||
"amount": int(gain) if isinstance(gain, (int, float)) else None,
|
||
"balance_after": int(points) if isinstance(points, (int, float)) else None,
|
||
"detail": {
|
||
"baseline": result.get("gift_points_baseline"),
|
||
"target": result.get("gift_points_target"),
|
||
"points_expire_at": expire_at,
|
||
"gold_balance": result.get("gold_balance"),
|
||
},
|
||
}
|
||
|
||
if task_type in ("confirm_bind", "confirm_esports_bind"):
|
||
return {
|
||
"event_type": EVENT_BIND_OK,
|
||
"title": "绑定角色" if task_type == "confirm_bind" else "电竞手册绑定",
|
||
"amount": None,
|
||
"balance_after": None,
|
||
"detail": {"raw_keys": sorted(result.keys())[:20]},
|
||
}
|
||
|
||
return None
|