1. 新增账号事件数据表 AccountEvent 与迁移版本 20261002_0040_account_events,支持审计 Cookie 变更、自动重登、健康检查及任务执行事件; 2. 后端新增 account_events_service 并扩展 /api/accounts 路由,支持事件查询、过滤与上报; 3. 前端新增 AccountDetailPage 账号详情页组件,支持账号元信息展示、事件历史瀑布流与快捷重登操作; 4. 修复 CK 重登与自动化定时任务中事件关联逻辑,补充 test_account_events 单元测试; 5. 新增生产服务器高负载排查分析报告及相关设计文档。
136 lines
4.3 KiB
Python
136 lines
4.3 KiB
Python
"""作业:把 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}",
|
||
}
|