fix(douyu): 修复斗鱼链路 P0/P1 隐患并增强 P2 运维队列可观测性

This commit is contained in:
yml
2026-11-29 14:10:24 +08:00
parent be7146a9ef
commit d12d9e02b3
51 changed files with 2510 additions and 561 deletions
@@ -9,7 +9,10 @@ from sqlalchemy.orm import Session
from ....models import AccountWorkItem, AutomationJob
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, run_account_sync_queue
from ...account_work_queue import expire_stale_login_work
from ...account_work_queue import (
expire_stale_login_work,
recover_stale_running_account_work,
)
JOB_KEY = "account_sync_queue"
@@ -34,7 +37,12 @@ def run_account_sync_queue_job(
) -> dict[str, Any]:
moment = datetime.now(UTC)
expired = expire_stale_login_work(db, now=moment)
if expired:
recovered_stale = recover_stale_running_account_work(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
now=moment,
)
if expired or recovered_stale:
db.commit()
result = run_account_sync_queue(
db,
@@ -42,11 +50,16 @@ def run_account_sync_queue_job(
)
if result.get("scanned"):
result["remaining"] = count_pending_work(db)
notes: list[str] = []
if recovered_stale:
result["recovered_stale"] = recovered_stale
notes.append(f"回收卡死工作 {recovered_stale} 条")
if expired:
result["expired_login"] = expired
notes.append(f"过期重登转人工 {expired} 条")
if notes:
result["message"] = (
f"{result.get('message') or '账号同步完成'},"
f"过期重登转人工 {expired} 条"
f"{result.get('message') or '账号同步完成'}," + ",".join(notes)
)
return result
@@ -48,7 +48,13 @@ from loguru import logger
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session
from ....models import AutomationJob, DouyuTask, ExecutionJob, ExecutionJobEvent
from ....models import (
AccountSyncRun,
AutomationJob,
DouyuTask,
ExecutionJob,
ExecutionJobEvent,
)
JOB_KEY = "douyu_tasks_retention"
@@ -74,6 +80,7 @@ NOISE_TASK_TYPES: tuple[str, ...] = (
DEFAULT_NOISE_DAYS = 7
DEFAULT_BUSINESS_DAYS = 90
DEFAULT_SYNC_RUN_DAYS = 14
DEFAULT_BATCH = 2000
DEFAULT_MAX_BATCHES = 50
@@ -167,10 +174,50 @@ def _delete_batch(
return deleted, candidates[-1].created_at, ids[-1]
def _delete_sync_run_batch(
db: Session,
*,
cutoff: datetime,
batch: int,
cursor_started_at: datetime | None = None,
cursor_id: int = 0,
) -> tuple[int, datetime | None, int]:
"""按游标分批清理过期 `account_sync_runs`,避免全表长时间持锁。"""
query = db.query(AccountSyncRun.id, AccountSyncRun.started_at).filter(
AccountSyncRun.started_at < cutoff
)
if cursor_started_at is not None:
query = query.filter(
or_(
AccountSyncRun.started_at > cursor_started_at,
and_(
AccountSyncRun.started_at == cursor_started_at,
AccountSyncRun.id > cursor_id,
),
)
)
candidates = (
query.order_by(AccountSyncRun.started_at.asc(), AccountSyncRun.id.asc())
.limit(batch)
.all()
)
if not candidates:
return 0, cursor_started_at, cursor_id
ids = [int(row.id) for row in candidates]
deleted = int(
db.query(AccountSyncRun)
.filter(AccountSyncRun.id.in_(ids))
.delete(synchronize_session=False)
or 0
)
return deleted, candidates[-1].started_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)
sync_run_days = _positive_int(config.get("sync_run_days"), DEFAULT_SYNC_RUN_DAYS)
batch = _positive_int(job.batch_size, DEFAULT_BATCH)
max_batches = _positive_int(config.get("max_batches"), DEFAULT_MAX_BATCHES)
@@ -179,6 +226,7 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
# 带 tzinfo 会被驱动按本地时区处理(参见设计文档里那次 8 小时偏移事故)。
noise_cutoff = (now - timedelta(days=noise_days)).replace(tzinfo=None)
business_cutoff = (now - timedelta(days=business_days)).replace(tzinfo=None)
sync_run_cutoff = (now - timedelta(days=sync_run_days)).replace(tzinfo=None)
total_deleted = 0
batches = 0
@@ -259,6 +307,27 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
batches += 1
db.commit()
deleted_sync_runs = 0
sync_run_cursor_started_at: datetime | None = None
sync_run_cursor_id = 0
while batches < max_batches:
deleted_runs, sync_run_cursor_started_at, sync_run_cursor_id = (
_delete_sync_run_batch(
db,
cutoff=sync_run_cutoff,
batch=batch,
cursor_started_at=sync_run_cursor_started_at,
cursor_id=sync_run_cursor_id,
)
)
if deleted_runs <= 0:
break
batches += 1
deleted_sync_runs += deleted_runs
db.commit()
if deleted_runs < batch:
break
# 注意措辞:这只说明「批次预算用光了」,**不等于**「确实还有积压」——
# 预算在上一档用完时,下一档根本没轮到执行,这里无法区分「没得删」和「没轮到」。
# 所以做成提示而非结论,措辞上也别谎称「仍有积压」。
@@ -283,9 +352,11 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
"deleted_rest": per_pass.get("rest", 0),
"deleted_execution_events": deleted_execution_events,
"deleted_execution_jobs": deleted_execution_jobs,
"deleted_sync_runs": deleted_sync_runs,
"batches": batches,
"noise_days": noise_days,
"business_days": business_days,
"sync_run_days": sync_run_days,
"batch_budget_exhausted": batch_budget_exhausted,
"message": message,
}
@@ -473,10 +473,13 @@ def stop_scheduler() -> None:
def scheduler_status() -> dict[str, Any]:
with _IN_FLIGHT_LOCK:
in_flight = sorted(_IN_FLIGHT)
return {
"enabled": automation_enabled(),
"running": _thread is not None and _thread.is_alive(),
"tick_seconds": TICK_SECONDS,
"job_interval_seconds": JOB_INTERVAL_SECONDS,
"registered": sorted(_REGISTRY),
"in_flight": in_flight,
}