feat(account): S5 业务事实直发事件 + 删掉收集器 + 任务日志保留策略

时间线从此覆盖**全部**业务事实,`douyu_tasks` 也有了可控的增长边界。

## 一、删掉收集器(它必然漏数据)

`jobs/account_events_collect.py` 连同 `_task_to_event` / `COLLECTED_TASK_TYPES` /
水位线一起删除,迁移 `20261004_0043` 清掉它的作业行。删除理由是实测出来的:

- **靠 allowlist 认业务类型,新增类型就静默丢**:原有名单只有 5 个,
  而 `exchange_esports_goods`(电竞兑换)、`exchange_xpd_goods`(和平小店兑换)、
  `pay_locked_order`(锁单支付)、`donate_esports_*`(电竞礼物积分)**从来没进过时间线**;
- **「任务 success」≠「业务真的发生了」**(见下);
- **字段路径靠抽样猜**:二维码充值的 `result` 里根本没有金额,收集器恒写
  `amount=None`,`recharge_total` 系统性少计;
- 作业默认 `enabled=False`,生产上一直没跑。

历史**不回填**(既有结论不变):需要历史走斗鱼侧权威接口
(`query_exchange_records` / `query_xpd_purchase_records` / `query_points` 都是现成任务类型)。

## 二、业务事实直发:命名构造函数

新增 `services/business_events.py`:`record_recharge` / `record_exchange` /
`record_points_credit` / `record_bind`。每类事实的字段、标题、金额符号只定义一次
(与 S4 的 `record_account_action`、`on_ck_verdict` 同一套路)。

**9 处成功点接线**:`exchange_goods` 真兑换分支、`exchange_esports_goods`、
`exchange_xpd_goods`、`pay_locked_order`、`create_gold_qr`(二维码 + 供应商轮询 +
**供应商回调**三条路径)、`donate_elite_gift`、`donate_esports_gift`、
`confirm_bind`、`confirm_esports_bind`。

**只记真实事实**(按你的决定):`exchange_goods` 里「预约到货 / 已预兑 / 预兑确认」
三条 success 分支**不发事件** —— 它们不消耗积分也没换到东西,旧收集器只按 status
收集,于是每预约一次就生成一条金额为空的 `exchange` 把 `exchange_count` 灌大。
`confirm_bind` 里「检测到账号本来就已绑定」那条也跳过。

## 三、修掉两个真 bug(都是钱账)

1. **到账判据 `!=` → `>`**(`douyu_runner_gold.py`):余额**下降**也算「鱼翅已到账」。
   批内并发(最高 10)时同账号送礼会消耗鱼翅,余额一变就被充值任务读成到账,
   **往台账记一笔根本没发生的充值**。
2. **供应商回调晚于 runner 超时**:原来守卫是「任务状态没被改过才更新」,
   于是 runner 先判 failed、回调随后说成功的那笔真金白银**永远不进时间线**。
   改成按**回调自己的终态**判断,并补发事件。

## 四、发射顺序:一个会静默丢事件的坑

`_mark_task` 内部 `db.commit()`,而 `emit` 用 `db.begin_nested()` **只 RELEASE
SAVEPOINT、不提交外层事务**;runner 的 `finally` 只 `close()`(未提交即回滚)。
所以**在 `_mark_task` 之后发事件会被静默丢弃,且 `emit` 仍返回 True**。
所有接线一律紧贴 `_mark_task(success)` **之前**,并加了源码扫描用例钉住
(已反向验证:故意挪到之后,用例立刻报出 file:line)。

## 五、`douyu_tasks` 保留策略(新增作业,默认关闭)

`jobs/douyu_tasks_retention.py`,两档:

| 档 | 保留 |
| --- | --- |
| 噪声查询(只读看一眼就走,且前端不拿它派生账号状态) | **7 天** |
| 其余一切(业务事实 + 状态派生依赖的查询 + **以后新增的类型**) | **90 天** |

长保留档用 `task_type NOT IN (噪声名单)` 表达 → **新增类型默认长保留**,不会因为
「忘了加名单」被误删(正是收集器翻车的反面)。在途任务(planned/pending/running)
**绝不删**;分批删避免长锁;两个窗口都能在作业 `config` 里改,不必发版。

⚠️ 「前端从任务列表反推账号当前状态」那几类查询(`query_xpd_bind_info` /
`query_esports_game_name` 等)**故意留在长保留档** —— 删早了工作台账号行会变
「未查」,那是把**当前显示**搞坏。根治要靠 §3.6 的状态列拆解(后续阶段)。
作业默认 `enabled=False`,由运维决定何时打开。

## 验证

- `TZ=Asia/Shanghai`:**450 passed / 6 skipped**(S4 后 426 → 净增 24)
- `TZ=UTC`(相关文件)101 passed;ruff check/format 全绿
- 前端 build 通过、lint 0 errors
- 真实开发库:迁移已应用(head `20261004_0043`,孤儿作业行已清);
  保留作业实跑确认「作业行默认关闭、SQL 在 MySQL 上正确、近期行不误删」
- **两处反向验证**:把 `record_bind` 挪到 `_mark_task` 之后 → 顺序用例报红;
  修掉 `registered_jobs()` 那个**假绿用例**(它返回 dict,原来的集合推导式
  遍历空字典恒成立),并在断言里加了反向确认

未做(后续):S6 账号页重构 + `bind_status` 三列拆解(做完才能把状态派生类查询
也纳入短保留)、S7 账号检测改账号维度、S8 丢 `login_tasks` 旧凭据列。
This commit is contained in:
yml2213
2026-10-04 16:00:42 +08:00
parent 253571730a
commit 6e729e7a80
18 changed files with 1438 additions and 545 deletions
+13 -105
View File
@@ -5,13 +5,20 @@
`accounts` 存**当前状态**(积分、余额、开通标记),这张表存**发生过什么**。
账号详情页 = 状态卡(读 `accounts`)+ 时间线(读本表)。
## 两条写入路径
## 唯一写入路径:直接发射
1. **直接发射**(`emit`):CK 失效/登录成功/重登、精英宝典与电竞手册开通 —— 这些
只在内存里出现过,不记就永远没有;
2. **增量收集**(`automation/jobs/account_events_collect.py`):充值/兑换/积分到账/绑定 ——
这些已经是 `douyu_tasks` 的行,由收集器按水位线往后提取,不动 runner 代码。
本模块只提供 `_task_to_event` 映射给它用。
业务事实**在它发生的那一刻**由业务代码发射(`emit` 或 `business_events` 里的命名
构造函数)。曾经有过第二条路径 —— 一个作业事后扫 `douyu_tasks.result` 的 JSON、
猜字段路径反推事件。那条路已经删掉,原因是它必然漏数据:
- 靠 allowlist 认业务类型 → 新增类型没人想起维护,**静默丢**(电竞兑换、和平小店
兑换、锁单支付、电竞礼物积分因此从来没进过时间线);
- 「任务 success」不等于「业务真的发生了」(预约、已绑定、未确认到账都会被标 success);
- 作业默认关闭,生产上它一直没跑。
历史**不从 `douyu_tasks` 回填**。需要历史时按斗鱼侧权威接口同步
(`query_exchange_records` / `query_xpd_purchase_records` / `query_points` 都是现成任务类型)
—— 宁可少,不可假。
## 两条硬约束
@@ -230,102 +237,3 @@ def emit_bulk(db: Session, events: list[dict[str, Any]]) -> int:
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
+19 -16
View File
@@ -6,12 +6,16 @@
from __future__ import annotations
from .jobs.account_events_collect import JOB_KEY as ACCOUNT_EVENTS_KEY
from .jobs.account_events_collect import run_account_events_collect
from .jobs.ck_health import JOB_KEY as CK_HEALTH_KEY
from .jobs.ck_health import run_ck_health
from .jobs.ck_relogin import JOB_KEY as CK_RELOGIN_KEY
from .jobs.ck_relogin import run_ck_relogin
from .jobs.douyu_tasks_retention import (
JOB_KEY as DOUYU_TASKS_RETENTION_KEY,
)
from .jobs.douyu_tasks_retention import (
run_douyu_tasks_retention,
)
from .scheduler import (
JobSpec,
automation_enabled,
@@ -27,9 +31,9 @@ from .scheduler import (
)
__all__ = [
"ACCOUNT_EVENTS_KEY",
"CK_HEALTH_KEY",
"CK_RELOGIN_KEY",
"DOUYU_TASKS_RETENTION_KEY",
"JobSpec",
"automation_enabled",
"ensure_jobs",
@@ -37,9 +41,9 @@ __all__ = [
"register_job",
"registered_jobs",
"reset_registry",
"run_account_events_collect",
"run_ck_health",
"run_ck_relogin",
"run_douyu_tasks_retention",
"run_due_jobs",
"run_job_now",
"scheduler_status",
@@ -50,6 +54,17 @@ __all__ = [
def register_default_jobs() -> None:
"""登记内置作业(幂等)。"""
register_job(
JobSpec(
key=DOUYU_TASKS_RETENTION_KEY,
title="任务日志清理",
# 一天一次足够:这是**清理**,不是业务;跑太勤只是白扫索引。
interval_seconds=24 * 3600,
batch_size=2000,
concurrency=1,
run=run_douyu_tasks_retention,
)
)
register_job(
JobSpec(
key=CK_RELOGIN_KEY,
@@ -75,15 +90,3 @@ def register_default_jobs() -> None:
run=run_ck_health,
)
)
register_job(
JobSpec(
key=ACCOUNT_EVENTS_KEY,
title="账号事件收集",
# interval_seconds 这里无实际意义(收集器每轮只按水位线往后取,
# 取不到就空转),保留一个值以复用现有调度与页面。
interval_seconds=10 * 60,
batch_size=500,
concurrency=1,
run=run_account_events_collect,
)
)
@@ -1,135 +0,0 @@
"""作业:把 douyu_tasks 里的业务操作增量收集成账号事件。
为什么用「收集」而不是在 runner 里直接发事件:充值/兑换/积分到账这些**已经是
`douyu_tasks` 的行**,再去改 8 个业务文件属于重复劳动;收集器只读不写业务表,
零侵入,且新老任务类型统一处理。
**不回填历史**(2026-10-03 已定):首次运行把水位线定在当前最大 id,
只往后收集。既有历史仍去各自页面查。
水位线存在本作业的 `automation_jobs.config` 里,进程重启不丢。
"""
from __future__ import annotations
import json
from typing import Any
from loguru import logger
from sqlalchemy import text
from sqlalchemy.orm import Session
from ....models import AutomationJob
from ...account_events_service import (
COLLECTED_TASK_TYPES,
_task_to_event,
emit,
)
JOB_KEY = "account_events_collect"
WATERMARK_FIELD = "watermark"
DEFAULT_BATCH = 500
def _load_config(job: AutomationJob) -> dict[str, Any]:
config = job.config
if isinstance(config, str):
try:
config = json.loads(config)
except ValueError:
config = {}
return dict(config) if isinstance(config, dict) else {}
def _save_watermark(db: Session, job: AutomationJob, watermark: int) -> None:
config = _load_config(job)
config[WATERMARK_FIELD] = int(watermark)
job.config = config
db.commit()
def run_account_events_collect(db: Session, job: AutomationJob) -> dict[str, Any]:
config = _load_config(job)
watermark = config.get(WATERMARK_FIELD)
if not isinstance(watermark, int):
# 首次运行:水位线定在「当前最大 id」= 从此刻起往后收集,**不回溯历史**。
max_id = db.execute(
text("SELECT COALESCE(MAX(id), 0) FROM douyu_tasks")
).scalar()
watermark = int(max_id or 0)
_save_watermark(db, job, watermark)
logger.info(
f"账号事件收集:首次运行,水位线定在 douyu_tasks.id={watermark}(不回溯)"
)
return {
"scanned": 0,
"skipped": 0,
"detail": {"written": 0, "watermark": watermark, "first_run": True},
"message": f"首次运行,水位线定在 {watermark}(不回溯历史)",
}
batch_size = max(int(job.batch_size or DEFAULT_BATCH), 1)
placeholders = ",".join(f":t{i}" for i in range(len(COLLECTED_TASK_TYPES)))
params: dict[str, Any] = {"wm": watermark, "limit": batch_size}
params.update({f"t{i}": t for i, t in enumerate(COLLECTED_TASK_TYPES)})
rows = (
db.execute(
text(
f"""
SELECT id, account_id, task_type, status, result, created_at, finished_at
FROM douyu_tasks
WHERE id > :wm AND task_type IN ({placeholders})
ORDER BY id ASC
LIMIT :limit
"""
),
params,
)
.mappings()
.all()
)
written = skipped = failed = 0
max_id = watermark
for row in rows:
max_id = max(max_id, int(row["id"]))
# 失败的任务不产生业务事实:兑换失败不该记「消耗了积分」。
if (row["status"] or "") != "success":
skipped += 1
continue
payload = _task_to_event(row["task_type"], row["result"])
if payload is None:
# 解析不出就跳过并告警,绝不让一行坏数据卡住整条水位线。
skipped += 1
logger.warning(
f"账号事件收集:无法解析 douyu_task {row['id']}({row['task_type']})"
)
continue
ok = emit(
db,
account_id=int(row["account_id"]),
occurred_at=row["finished_at"] or row["created_at"],
source="task",
source_ref=f"douyu_task:{row['id']}",
**payload,
)
if ok:
written += 1
else:
failed += 1
if rows:
_save_watermark(db, job, max_id)
return {
"scanned": len(rows),
"skipped": skipped,
"detail": {
"written": written,
"failed": failed,
"watermark": max_id,
},
"message": f"本轮收集 {written} 条事件,跳过 {skipped} 条,水位线 {max_id}",
}
@@ -0,0 +1,207 @@
"""作业:清理 `douyu_tasks` 的历史任务日志。
## 为什么需要
`douyu_tasks` 是**执行日志**,不是账号历史。它按天增长(生产实测 222,679 行 /
687MB,且绝大多数是例行查询),而其中真正有长期价值的业务事实,S5 之后都会
由业务代码在发生那一刻写进 `account_events`(体量小几个数量级)。
所以这里只做一件事:**按任务类型的价值分档,把过期的执行日志删掉。**
## 分档依据(关键设计)
不是「按时间一刀切」,而是按「这条日志里的 `result` 还有没有人需要」分三档:
| 档 | 判定 | 默认保留 | 说明 |
| --- | --- | --- | --- |
| **噪声查询** | 只读、看一眼就走,且前端**不**用它的 `result` 派生账号状态 | 7 天 | 体量最大的就是这类(`query_limited_goods` 单类 6.7 万行) |
| **状态派生** | 前端从任务列表反推账号当前状态时要读它(`latest*ByAccount`) | 90 天 | 删早了工作台账号行的「已绑定/未绑定」会变成「未查」 |
| **业务事实** | 真花钱/花积分/改变账号归属的动作 | 90 天 | 90 天后仍有 `account_events` 兜底 |
⚠️ **为什么「状态派生」类不能按 7 天删**:工作台是从任务列表**反推**账号状态的
(`DouyuTasksPage` 的 `latestConfirmBindTaskByAccount` 等),而且明确要求
`task.result` 非空。这是历史包袱(和 `bind_status` 同源:账号的「现在是什么」
存在执行日志里),设计文档 §3.6 的状态列拆解才是根治。在拆解完成之前,
这里保守地把这类查询留长一点 —— 否则会把「当前显示」搞坏,那不是在清历史。
两类窗口都可以在 `/automation` 页面按作业改(`config.noise_days` /
`config.business_days`),不必发版。
## 安全约束
- **绝不删在途任务**(`planned` / `pending` / `running`)—— 批次线程可能正拿着它;
- 分批删(每批 `batch_size` 行、最多 `max_batches` 批),避免长事务长时间锁表;
- 不删行、只删「过期的整行」:不做「把 result 清空保留行」这种半吊子操作,
因为部分前端派生**明确要求 result 非空**,清空等于制造「有行但读不出状态」的
更隐蔽的坏状态;
- 作业**默认关闭**(`ensure_jobs` 建行时 enabled=False),由运维在页面上打开。
"""
from __future__ import annotations
import json
from datetime import UTC, datetime, timedelta
from typing import Any
from loguru import logger
from sqlalchemy import text
from sqlalchemy.orm import Session
from ....models import AutomationJob
JOB_KEY = "douyu_tasks_retention"
#: 只读、看一眼就走,且前端**不**拿它派生账号状态 → 短保留。
#: 体量最大的就在这一类(`query_limited_goods` / `query_change_bind_time`)。
NOISE_TASK_TYPES: tuple[str, ...] = (
"query_limited_goods",
"query_change_bind_time",
"query_gold_balance",
"query_xpd_balance",
"query_xpd_fragments",
"query_points",
"refresh_goods",
"refresh_esports_goods",
"refresh_xpd_goods",
"prefetch_csrf_token",
)
DEFAULT_NOISE_DAYS = 7
DEFAULT_BUSINESS_DAYS = 90
DEFAULT_BATCH = 2000
DEFAULT_MAX_BATCHES = 50
#: 在途任务绝不可删:批次线程正拿着这些行。
IN_FLIGHT_STATUSES = ("planned", "pending", "running")
def _load_config(job: AutomationJob) -> dict[str, Any]:
config = job.config
if isinstance(config, str):
try:
config = json.loads(config)
except ValueError:
config = {}
return dict(config) if isinstance(config, dict) else {}
def _positive_int(value: Any, default: int) -> int:
try:
parsed = int(value)
except (TypeError, ValueError):
return default
return parsed if parsed > 0 else default
def _delete_batch(
db: Session,
*,
task_types: tuple[str, ...],
cutoff: datetime,
batch: int,
negate: bool = False,
) -> int:
"""删一批过期行,返回删除条数。
`negate=True` 时语义变成「**除这些类型之外**的都在这一档」—— 长保留档就是这么
表达的。这样做有个重要的安全属性:**新增的任务类型默认落在长保留档**,
不会因为「忘了往某个列表里加」而在 7 天后被误删(收集器当年就是反过来,
忘了加 allowlist 就静默丢数据)。
`LIMIT` 让单条语句不会长时间持锁。
"""
if not task_types:
return 0
placeholders = ", ".join(f":t{i}" for i in range(len(task_types)))
status_placeholders = ", ".join(f":s{i}" for i in range(len(IN_FLIGHT_STATUSES)))
operator = "NOT IN" if negate else "IN"
params: dict[str, Any] = {
"cutoff": cutoff,
"limit": batch,
**{f"t{i}": t for i, t in enumerate(task_types)},
**{f"s{i}": s for i, s in enumerate(IN_FLIGHT_STATUSES)},
}
result = db.execute(
text(
f"""
DELETE FROM douyu_tasks
WHERE task_type {operator} ({placeholders})
AND status NOT IN ({status_placeholders})
AND created_at < :cutoff
LIMIT :limit
"""
),
params,
)
return int(result.rowcount or 0)
def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]:
config = _load_config(job)
noise_days = _positive_int(config.get("noise_days"), DEFAULT_NOISE_DAYS)
business_days = _positive_int(config.get("business_days"), DEFAULT_BUSINESS_DAYS)
batch = _positive_int(job.batch_size, DEFAULT_BATCH)
max_batches = _positive_int(config.get("max_batches"), DEFAULT_MAX_BATCHES)
now = datetime.now(UTC)
# 传 naive UTC:created_at 是 UTCDateTime 列,裸 SQL 参数不经过类型转换,
# 带 tzinfo 会被驱动按本地时区处理(参见设计文档里那次 8 小时偏移事故)。
noise_cutoff = (now - timedelta(days=noise_days)).replace(tzinfo=None)
business_cutoff = (now - timedelta(days=business_days)).replace(tzinfo=None)
total_deleted = 0
batches = 0
# 两档:噪声查询只留 noise_days;**其余一切**(业务事实 + 前端状态派生依赖的
# 查询 + 以后新增的类型)留 business_days。
passes = (
(noise_cutoff, NOISE_TASK_TYPES, False, "noise"),
(business_cutoff, NOISE_TASK_TYPES, True, "rest"),
)
per_pass: dict[str, int] = {}
for cutoff, task_types, negate, label in passes:
deleted_this_pass = 0
while batches < max_batches:
deleted = _delete_batch(
db,
task_types=task_types,
cutoff=cutoff,
batch=batch,
negate=negate,
)
batches += 1
total_deleted += deleted
deleted_this_pass += deleted
db.commit()
if deleted < batch:
break
per_pass[label] = deleted_this_pass
# 注意措辞:这只说明「批次预算用光了」,**不等于**「确实还有积压」——
# 预算在上一档用完时,下一档根本没轮到执行,这里无法区分「没得删」和「没轮到」。
# 所以做成提示而非结论,措辞上也别谎称「仍有积压」。
batch_budget_exhausted = batches >= max_batches
if batch_budget_exhausted:
logger.warning(
"任务日志清理用光了批次预算({} 批,共删 {} 条);"
"若日志量持续很大,可调大 max_batches 或 batch_size",
max_batches,
total_deleted,
)
message = (
f"清理 {total_deleted} 条任务日志"
f"(噪声>{noise_days}天 / 其余>{business_days}天,{batches} 批)"
)
logger.info(message)
return {
"scanned": total_deleted,
"deleted": total_deleted,
"deleted_noise": per_pass.get("noise", 0),
"deleted_rest": per_pass.get("rest", 0),
"batches": batches,
"noise_days": noise_days,
"business_days": business_days,
"batch_budget_exhausted": batch_budget_exhausted,
"message": message,
}
+251
View File
@@ -0,0 +1,251 @@
"""业务事实的**命名构造**:充值 / 兑换 / 积分到账 / 绑定。
## 为什么单独一个模块
`emit()` 只负责「往时间线写一条」,它不知道「一次兑换」到底该长什么样。
以前这件事由收集器从 `douyu_tasks.result` 的 JSON 里**反推**(猜字段路径),
结果是:
- 新增业务类型没人想起改 allowlist → **静默丢数据**
(电竞兑换、和平小店兑换、锁单支付、电竞礼物积分从来没进过时间线);
- 同一件事的字段口径散在 runner 与收集器两处,容易分叉;
- `success` 不等于「业务真的发生了」时,把假成功也记成事实。
现在反过来:**业务代码在动作成功的那一刻,用这里的构造函数声明事实**。
每类事实的字段、标题、金额符号只定义一次。
## 两条硬规则
1. **必须紧贴 `_mark_task(..., "success", ...)` 之前调用。**
`_mark_task` 内部 `db.commit()`,而 `emit()` 用 `db.begin_nested()` 只 RELEASE
SAVEPOINT、不提交外层事务;`douyu_runner` 的 `finally` 只 `close()`(未提交即回滚)。
在 `_mark_task` **之后**发事件会被静默回滚 —— 而且 `emit()` 返回 True、无任何日志。
放在之前还有个好处:事件与任务状态**同一次提交**,原子。
2. **幂等键用 `task_ref(task.id)`**,与旧收集器的 key 完全一致。
于是迁移窗口内「直发」与「仍在跑的收集器」会自动去重,可以安全并存后再删作业。
⚠️ 不要用秒级时间戳当幂等键:撞唯一键会让 `emit()` 静默吞掉事件
(见 `account_lifecycle` 里那段复盘)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy.orm import Session
from ..models import Account
from .account_events_service import (
CATEGORY_BUSINESS,
EVENT_BIND_OK,
EVENT_EXCHANGE,
EVENT_POINTS_CREDIT,
EVENT_RECHARGE,
emit,
)
def task_ref(task_id: int) -> str:
"""业务事件的幂等键:一条任务行对应一条事实。
与旧收集器(`f"douyu_task:{row['id']}"`)**完全一致**,所以直发与收集器
同时观测到同一笔业务时只会写一条 —— 这让「先直发、观察一段、再删收集器」
成为安全的迁移路径。
"""
return f"douyu_task:{int(task_id)}"
def record_recharge(
db: Session,
account: Account,
*,
task_id: int,
amount: int | None,
occurred_at: datetime | None = None,
order_id: str = "",
supplier_order_id: str = "",
channel: str = "",
douyu_uid: str = "",
balance_after: int | None = None,
confirmed: bool = True,
) -> bool:
"""充值鱼翅到账。
`amount` 用**本地已知的充值金额**,不要从 `result` 里找 —— 二维码链路的
`result` 里根本没有金额(`create_gold_qr` 只返回 `pay_url/token/raw`),
旧收集器因此在二维码充值上恒写 `amount=None`,导致 `accounts.recharge_total`
系统性少计。
`confirmed=False` 表示只有供应商的终态回执、没有核对斗鱼余额变化。
"""
title = f"充值 {amount}" if amount is not None else "充值到账"
if not confirmed:
title += "(供应商回执)"
return emit(
db,
account_id=account.id,
event_type=EVENT_RECHARGE,
title=title,
category=CATEGORY_BUSINESS,
occurred_at=occurred_at,
amount=amount,
balance_after=balance_after,
detail={
"order_id": order_id,
"supplier_order_id": supplier_order_id,
"channel": channel,
"douyu_uid": douyu_uid,
"confirmed": confirmed,
},
source="douyu_task",
subject_type="recharge",
subject_key=order_id or supplier_order_id or "",
source_ref=task_ref(task_id),
)
def record_exchange(
db: Session,
account: Account,
*,
task_id: int,
name: str,
score: int | None,
occurred_at: datetime | None = None,
commodity_id: str = "",
order_id: str = "",
exchange_id: str = "",
game_name: str = "",
game_channel: str = "",
points_after: int | None = None,
scope: str = "elite",
) -> bool:
"""商品/皮肤兑换成功 —— **只在真的消耗了积分并兑换成功时调用**。
注意「预约到货 / 已预兑 / 预兑确认」这三类也把任务标成 `success`,但它们
**不消耗积分、也没兑换到东西**,绝不能走这里(旧收集器只按 `status=="success"`
过滤,于是每预约一次就生成一条金额为空的 `exchange`,把 `exchange_count` 灌大)。
`score` 为负写入 `amount`(消耗),`points_after` 是兑换后的积分余额。
"""
return emit(
db,
account_id=account.id,
event_type=EVENT_EXCHANGE,
title=f"兑换 {name}" if name else "兑换",
category=CATEGORY_BUSINESS,
occurred_at=occurred_at,
amount=-int(score) if isinstance(score, (int, float)) else None,
balance_after=points_after,
detail={
"commodity_id": commodity_id,
"commodity_name": name,
"order_id": order_id,
"exchange_id": exchange_id,
"game_name": game_name,
"game_channel": game_channel,
"score": score,
"scope": scope,
},
source="douyu_task",
subject_type="commodity",
subject_key=commodity_id or name or "",
source_ref=task_ref(task_id),
)
def record_points_credit(
db: Session,
account: Account,
*,
task_id: int,
gain: int | None,
occurred_at: datetime | None = None,
points_after: int | None = None,
expire_at: Any = None,
confirmed: bool = True,
source_label: str = "精英令",
) -> bool:
"""积分到账(送礼/任务发放)。
`confirmed` 必须如实反映「有没有真的看到积分涨上去」。送礼任务在**没确认**
到账时也会把任务标成 `success`(消息里加一句「(未确认涨到 X)」),旧收集器
照样把 `gift_points_expected_gain` 当成事实写进台账 —— 把「预期」记成了「已到账」。
这里保留事件(延迟到账也是真实发生的发放),但**把 `confirmed` 明确落进
detail**:宁可标清楚是未确认,也不假装它是确认过的数字。
"""
title = f"积分到账 +{gain}" if gain is not None else "积分到账"
title = f"{source_label}{title}"
if not confirmed:
title += "(未确认)"
return emit(
db,
account_id=account.id,
event_type=EVENT_POINTS_CREDIT,
title=title,
category=CATEGORY_BUSINESS,
occurred_at=occurred_at,
amount=int(gain) if isinstance(gain, (int, float)) else None,
balance_after=points_after,
detail={
"confirmed": confirmed,
"expire_at": expire_at,
"source": source_label,
},
source="douyu_task",
subject_type="points",
source_ref=task_ref(task_id),
)
def record_bind(
db: Session,
account: Account,
*,
task_id: int,
scope: str,
role_name: str = "",
occurred_at: datetime | None = None,
act_alias: str = "",
rebind: bool = False,
weak: bool = False,
) -> bool:
"""角色绑定 / 换绑**真的发生了**。
⚠️ 只在「确认接口成功」时调用。`confirm_bind` 里还有一条分支是
「检测到账号**本来就已经绑定**」——它什么都没做也把任务标成 `success`,
旧收集器把每次重复点「确认绑定」都记成一条 `bind_ok`。
`weak=True` 表示确认接口成功、但回查拿不到结果(没能亲眼确认生效),
仍然记,但标出来。
"""
label = "换绑" if rebind else "绑定"
scope_label = {"elite": "精英宝典", "esports": "电竞手册", "peace": "和平小店"}.get(
scope, scope
)
title = f"{scope_label}{label}"
if role_name:
title += f":{role_name}"
if weak:
title += "(未回查确认)"
return emit(
db,
account_id=account.id,
event_type=EVENT_BIND_OK,
title=title,
category=CATEGORY_BUSINESS,
occurred_at=occurred_at,
detail={
"scope": scope,
"role_name": role_name,
"act_alias": act_alias,
"rebind": rebind,
"confirmed": not weak,
},
source="douyu_task",
subject_type=f"{scope}_role",
subject_key=role_name or "",
source_ref=task_ref(task_id),
)
+51 -1
View File
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient, DouyuActivityError
from ..models import Account, DouyuTask
from .business_events import record_bind
DOUYU_LEGACY_BIND_ACT_ALIAS = "20250213NQCYX"
DOUYU_BIND_ROLE_POLL_SECONDS = 65
@@ -918,6 +919,18 @@ class BindMixin:
else:
account.bind_status = "bind_confirmed"
account.updated_at = datetime.now(UTC)
# 确认接口成功了,但回查抛异常 —— 没能亲眼看到绑定生效。
# 仍然记(确认请求确实发出且成功),但 weak=True 标出来。
record_bind(
db,
account,
task_id=task.id,
scope="elite",
role_name=role_name,
act_alias=use_confirm_alias,
rebind=_bind_is_rebind(before_snapshot),
weak=True,
)
self._mark_task(
db,
task,
@@ -941,6 +954,18 @@ class BindMixin:
after_snapshot = self._bind_snapshot(after)
final_role_name = after_snapshot["role_name"] or role_name
self._apply_bind_info_to_account(account, after, "bind_confirmed")
# 强事实:确认接口成功 + 回查命中已生效绑定。
# ⚠️ 上面还有一条 success 是「检测到账号**本来就已经绑定**」(什么都没做),
# 那条**不发事件** —— 否则用户每点一次「确认绑定」时间线就多一条假的绑定记录。
record_bind(
db,
account,
task_id=task.id,
scope="elite",
role_name=final_role_name,
act_alias=use_confirm_alias,
rebind=_bind_is_rebind(after_snapshot),
)
self._mark_task(
db,
task,
@@ -1089,11 +1114,23 @@ class BindMixin:
return
self._apply_esports_bind_info_to_account(account, after_state, "esports_bound")
# 业务事实在这一刻成立:确认接口成功 + 回查 esports_bound 为真。
# 必须在 _mark_task 之前发 —— 它内部 commit,而 emit 只 RELEASE SAVEPOINT、
# 不提交外层事务,runner 的 finally 只 close(未提交即回滚),之后发会被静默丢弃。
role_text = self._esports_role_text(after_state) or ""
record_bind(
db,
account,
task_id=task.id,
scope="esports",
role_name=role_text,
act_alias=act_alias,
)
self._mark_task(
db,
task,
"success",
f"电竞手册绑定成功: {self._esports_role_text(after_state) or '-'}",
f"电竞手册绑定成功: {role_text or '-'}",
result,
)
@@ -1333,3 +1370,16 @@ class BindMixin:
f"{role_name} {status_text} | act={source_alias or '-'}",
result,
)
def _bind_is_rebind(snapshot: dict) -> bool:
"""这次是「换绑」还是「首次绑定」。
`before_bound` 命中说明确认前**该账号已有一个生效绑定**,本次是把角色换掉;
否则是首次绑定。旧收集器不区分,时间线上看不出「换绑」这件事。
"""
return bool(
snapshot.get("bound_act")
or snapshot.get("bind_confirmed")
or snapshot.get("role_name")
)
+59 -3
View File
@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..models import Account, DouyuTask
from .business_events import record_points_credit
DOUYU_GIFT_POINTS_REFRESH_TIMES = 3
DOUYU_GIFT_POINTS_REFRESH_INTERVAL = 2
@@ -178,11 +179,23 @@ class DonateMixin:
account.esports_bind_status = "esports_gift_donated"
account.updated_at = datetime.now(UTC)
confirmed = bool(result.get("esports_points_changed"))
message = f"赠送{gift_name}成功: {gift_count}"
if account.gold_balance is not None:
message += f",鱼翅余额: {account.gold_balance}"
if account.esports_points is not None:
message += f",电竞积分: {account.esports_points}"
# 电竞礼物同样产生积分到账 —— 这一类此前**从来不在收集范围**
# (不在 COLLECTED_TASK_TYPES 里),时间线上一直是空白。
record_points_credit(
db,
account,
task_id=task.id,
gain=_esports_gift_points(result, baseline_points),
points_after=account.esports_points,
confirmed=confirmed,
source_label=gift_name,
)
self._mark_task(db, task, "success", message, result)
def _execute_donate_esports_chicken_gift(
@@ -277,10 +290,53 @@ class DonateMixin:
message = f"赠送精英令成功: {gift_count}"
if account.gold_balance is not None:
message += f",鱼翅余额: {account.gold_balance}"
confirmed = bool(result.get("gift_points_confirmed"))
if account.points is not None:
message += f",积分: {account.points}"
if result.get("gift_points_target") is not None and not result.get(
"gift_points_confirmed"
):
if result.get("gift_points_target") is not None and not confirmed:
message += f"(未确认涨到 {result['gift_points_target']})"
# 积分到账是业务事实。**未确认也记,但把 confirmed 明确写进 detail** ——
# 旧收集器把「预期涨幅」当既成事实写进台账(未确认时也记 +980),
# 那是把预期记成到账。这里宁可标清楚,也不假装它是确认过的数字。
# 金额用本地可等价重算的值(1 个精英令 ≈ 10 分),不再依赖 result 里的字段。
record_points_credit(
db,
account,
task_id=task.id,
gain=max(0, gift_count) * 10,
points_after=account.points,
expire_at=_points_expire_at(result),
confirmed=confirmed,
source_label="精英令",
)
self._mark_task(db, task, "success", message, result)
def _points_expire_at(result: dict) -> object:
"""从积分查询结果里取出到期时间(同样是为了给时间线留全信息)。
旧收集器走的是 `result["points_query"]["raw"]["data"]["willExpireTime"]` 这条
「猜出来」的路径;这里收敛成一个具名函数,只有它知道那段结构。
"""
query = result.get("points_query")
if not isinstance(query, dict):
return None
raw = query.get("raw")
data = raw.get("data") if isinstance(raw, dict) else None
return data.get("willExpireTime") if isinstance(data, dict) else None
def _esports_gift_points(result: dict, baseline_points: int | None) -> int | None:
"""电竞礼物带来的积分增量。
以**实际观测到的积分变化**为准(`esports_points_after_gift` - 基线),
而不是像旧收集器那样去读一个「预期涨幅」。观测不到就返回 None ——
金额宁可空着,也不要写一个猜出来的数字进台账。
"""
after = result.get("esports_points_after_gift")
if not isinstance(after, (int, float)) or not isinstance(
baseline_points, (int, float)
):
return None
delta = int(after) - int(baseline_points)
return delta if delta > 0 else None
+34 -1
View File
@@ -18,6 +18,7 @@ from core.douyu import (
)
from ..models import Account, DouyuTask
from .business_events import record_recharge
from .douyu_runner_core import DOUYU_PAYMENT_POLL_INTERVAL, DOUYU_PAYMENT_POLL_SECONDS
from .douyu_service import update_account_profile_from_cookie
@@ -92,8 +93,12 @@ class GoldMixin:
if self._stop.wait(DOUYU_PAYMENT_POLL_INTERVAL):
break
continue
# ⚠️ 判据必须是 `>`(余额**增加**)而不是 `!=`。
# 原来用 `!=`,于是余额**下降**也算「到账」:批内并发(concurrency
# 最高 10)时同账号的送礼任务会消耗鱼翅,余额一变就被这个充值任务
# 读成「鱼翅已到账」,往台账里记一笔根本没发生的充值。
changed = last_gold is not None and (
baseline_gold is None or last_gold != baseline_gold
baseline_gold is None or last_gold > baseline_gold
)
if changed:
result["payment_polling"] = False
@@ -279,6 +284,18 @@ class GoldMixin:
if recharged:
account.bind_status = "gold_recharged"
account.updated_at = datetime.now(UTC)
# 金额用**本地变量 amount**:二维码链路的 result 里没有金额
# (create_gold_qr 只返回 pay_url/token/raw),旧收集器在这里恒写
# amount=None,导致 accounts.recharge_total 系统性少计。
record_recharge(
db,
account,
task_id=task.id,
amount=amount,
channel=channel,
balance_after=account.gold_balance,
confirmed=True,
)
self._mark_task(
db,
task,
@@ -426,6 +443,22 @@ class GoldMixin:
if status == 2:
account.bind_status = "gold_recharged"
account.updated_at = datetime.now(UTC)
# 幂等键与**供应商回调**(routers/douyu.py)完全一致 —— 两条路径都可能
# 观测到同一笔成功(_wait_supplier_gold_order 会采纳回调结果再 mark 一次),
# 同一个 source_ref 天然去重。
record_recharge(
db,
account,
task_id=task.id,
amount=amount,
order_id=str(result.get("out_order_id") or ""),
supplier_order_id=str(result.get("order_id") or ""),
channel="supplier_api",
douyu_uid=str(result.get("douyu_uid") or ""),
balance_after=account.gold_balance,
# 供应商终态成功 ≠ 斗鱼余额已变,如实标注
confirmed=False,
)
self._mark_task(db, task, "success", "供应商直充成功", result)
return
if status in {3, 4}:
@@ -12,6 +12,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient, DouyuActivityError
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
from .business_events import record_exchange
# 兑换节奏与重试(对齐 8.30 浏览器抓包:锁单->支付间隔约 2.2~4.2s;火爆类错误要长退避而不是秒级连打)
DOUYU_EXCHANGE_PRE_CREATE_JITTER = (0.3, 1.2)
@@ -204,6 +205,29 @@ class GoodsMixin:
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._push_log("warning", f"支付锁单后刷新积分失败: {exc}")
# 两步式兑换(lock_goods → pay_locked_order)的**支付**这一步才是真兑换。
# 这一步此前从不发事件,时间线上只有「锁单」没有「支付」。
# `pay_exchange_order` 的响应里没有 score,用商品快照上的标价。
score = None
if goods is not None and isinstance(goods.score, (int, float)):
num = payment.get("exchange_num")
score = int(goods.score) * (
int(num) if isinstance(num, (int, float)) else 1
)
record_exchange(
db,
account,
task_id=task.id,
name=(goods.name if goods else "") or commodity_id or order_id,
score=score,
commodity_id=commodity_id,
order_id=order_id,
exchange_id=str(payment.get("exchange_id") or ""),
game_name=account.game_name or "",
game_channel=account.game_channel or "",
points_after=account.points,
scope="elite",
)
self._mark_task(
db,
task,
@@ -495,6 +519,24 @@ class GoodsMixin:
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self._push_log("warning", f"兑换后刷新积分失败: {exc}")
# ⚠️ **只有这一条 success 是真的兑换**。同一个 handler 里还有三条
# 「预约到货 / 已预兑 / 预兑确认」的 success —— 它们不消耗积分、也没换到东西,
# 所以**不发事件**。旧收集器只按 status=="success" 收集,导致每预约一次
# 就生成一条金额为空的 exchange,把 accounts 的 exchange_count 灌大。
record_exchange(
db,
account,
task_id=task.id,
name=name,
score=locked.get("score"),
commodity_id=commodity_id,
order_id=str(locked.get("order_id") or ""),
exchange_id=str(payment.get("exchange_id") or ""),
game_name=account.game_name or "",
game_channel=account.game_channel or "",
points_after=(points_refresh or {}).get("points"),
scope="elite",
)
self._mark_task(
db,
task,
@@ -587,6 +629,28 @@ class GoodsMixin:
result["account_name"] = (
account.nickname or account.username or account.uid or f"#{account.id}"
)
# 电竞皮肤兑换 —— **此前从不发事件**(不在旧收集器的 allowlist 里),
# 时间线上一直是空白。
# 消耗的电竞积分用「兑换前后积分差」实测,而不是读猜测的字段。
after_points = result.get("esports_points_after_exchange")
spent = (
int(baseline_points) - int(after_points)
if isinstance(baseline_points, (int, float))
and isinstance(after_points, (int, float))
else None
)
record_exchange(
db,
account,
task_id=task.id,
name=name,
score=spent if spent and spent > 0 else None,
commodity_id=commodity_id,
game_name=account.esports_game_name or "",
game_channel=account.esports_game_channel or "",
points_after=account.esports_points,
scope="esports",
)
self._mark_task(db, task, "success", message, result)
def _execute_query_limited_goods(
+16
View File
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient, DouyuActivityError
from ..models import Account, DouyuTask, DouyuXpdGoodsSnapshot
from .business_events import record_exchange
DOUYU_XPD_BIND_POLL_SECONDS = 300
DOUYU_XPD_BIND_POLL_INTERVAL = 5
@@ -581,6 +582,21 @@ class XpdMixin:
"currency": currency,
}
)
# 和平小店兑换 —— 此前从不发事件(不在旧收集器的 allowlist 里)。
# 消耗的是点券或扭蛋碎片,不是积分;金额用本地已知的 price(快照标价,
# 已在上面校验过 > 0),作用域标成 peace 以便和精英/电竞区分。
record_exchange(
db,
account,
task_id=task.id,
name=goods.name or commodity_id,
score=price,
commodity_id=commodity_id,
game_name=display_role,
game_channel=channel,
points_after=result.get("new_balance"),
scope="peace",
)
self._mark_task(
db,
task,