"""作业:清理 `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=True),避免执行日志无限增长; 运维仍可在页面上关闭。 """ from __future__ import annotations import json from datetime import UTC, datetime, timedelta from typing import Any from loguru import logger from sqlalchemy import and_, or_ from sqlalchemy.orm import Session from ....models import AutomationJob, DouyuTask, ExecutionJob, ExecutionJobEvent JOB_KEY = "douyu_tasks_retention" #: 已淘汰但仍可能有历史行的任务类型。保留在清理名单中, #: 避免下线入口后旧日志永久占用空间。 RETIRED_NOISE_TASK_TYPES: tuple[str, ...] = ( "query_limited_goods", "refresh_goods", ) #: 只读、看一眼就走,且前端**不**拿它派生账号状态 → 短保留。 NOISE_TASK_TYPES: tuple[str, ...] = ( *RETIRED_NOISE_TASK_TYPES, "query_change_bind_time", "query_gold_balance", "query_xpd_balance", "query_xpd_fragments", "query_points", "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") #: 只清理明确结束的状态。未知/新增状态默认保留,避免未来状态机扩展后被误删。 TERMINAL_STATUSES = ( "success", "failed", "error", "stopped", "timeout", "cancelled", ) 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, cursor_created_at: datetime | None = None, cursor_id: int = 0, ) -> tuple[int, datetime | None, int]: """按时间/主键游标取一批过期 ID,删除后返回新游标。 `negate=True` 时语义变成「**除这些类型之外**的都在这一档」—— 长保留档就是这么 表达的。这样做有个重要的安全属性:**新增的任务类型默认落在长保留档**, 不会因为「忘了往某个列表里加」而在 7 天后被误删(收集器当年就是反过来, 忘了加 allowlist 就静默丢数据)。 先取有限 ID 再按主键删除,单条语句不会长时间持锁;游标保证跨批次只向前扫。 """ if not task_types: return 0, cursor_created_at, cursor_id type_filter = ( ~DouyuTask.task_type.in_(task_types) if negate else DouyuTask.task_type.in_(task_types) ) query = db.query(DouyuTask.id, DouyuTask.created_at).filter( type_filter, DouyuTask.status.in_(TERMINAL_STATUSES), DouyuTask.created_at < cutoff, ) if cursor_created_at is not None: query = query.filter( or_( DouyuTask.created_at > cursor_created_at, and_( DouyuTask.created_at == cursor_created_at, DouyuTask.id > cursor_id, ), ) ) candidates = ( query.order_by(DouyuTask.created_at.asc(), DouyuTask.id.asc()) .limit(batch) .all() ) if not candidates: return 0, cursor_created_at, cursor_id ids = [int(row.id) for row in candidates] deleted = int( db.query(DouyuTask) .filter(DouyuTask.id.in_(ids)) .delete(synchronize_session=False) or 0 ) return deleted, candidates[-1].created_at, ids[-1] 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 cursor_created_at: datetime | None = None cursor_id = 0 while batches < max_batches: deleted, cursor_created_at, cursor_id = _delete_batch( db, task_types=task_types, cutoff=cutoff, batch=batch, negate=negate, cursor_created_at=cursor_created_at, cursor_id=cursor_id, ) batches += 1 total_deleted += deleted deleted_this_pass += deleted db.commit() if deleted < batch: break per_pass[label] = deleted_this_pass deleted_execution_events = 0 deleted_execution_jobs = 0 if batches < max_batches: event_ids = [ int(row[0]) for row in ( db.query(ExecutionJobEvent.id) .filter(ExecutionJobEvent.created_at < business_cutoff) .order_by(ExecutionJobEvent.id.asc()) .limit(batch) .all() ) ] if event_ids: deleted_execution_events = int( db.query(ExecutionJobEvent) .filter(ExecutionJobEvent.id.in_(event_ids)) .delete(synchronize_session=False) or 0 ) batches += 1 db.commit() if batches < max_batches: job_ids = [ int(row[0]) for row in ( db.query(ExecutionJob.id) .filter( ExecutionJob.status.in_(("succeeded", "failed", "cancelled")), ExecutionJob.finished_at.isnot(None), ExecutionJob.finished_at < business_cutoff, ) .order_by(ExecutionJob.id.asc()) .limit(batch) .all() ) ] if job_ids: deleted_execution_jobs = int( db.query(ExecutionJob) .filter(ExecutionJob.id.in_(job_ids)) .delete(synchronize_session=False) or 0 ) batches += 1 db.commit() # 注意措辞:这只说明「批次预算用光了」,**不等于**「确实还有积压」—— # 预算在上一档用完时,下一档根本没轮到执行,这里无法区分「没得删」和「没轮到」。 # 所以做成提示而非结论,措辞上也别谎称「仍有积压」。 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), "deleted_execution_events": deleted_execution_events, "deleted_execution_jobs": deleted_execution_jobs, "batches": batches, "noise_days": noise_days, "business_days": business_days, "batch_budget_exhausted": batch_budget_exhausted, "message": message, }