perf(automation): 持久队列驱动并优化履约热路径

This commit is contained in:
yml
2026-11-23 15:07:31 +08:00
parent 11c2a0dba7
commit 2549511598
31 changed files with 1658 additions and 235 deletions
@@ -24,6 +24,12 @@ from .jobs.account_sync_queue import (
from .jobs.account_sync_queue import (
run_account_sync_queue_job,
)
from .jobs.account_value_projection import (
JOB_KEY as ACCOUNT_VALUE_PROJECTION_KEY,
)
from .jobs.account_value_projection import (
run_account_value_projection,
)
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
@@ -60,6 +66,7 @@ __all__ = [
"ACCOUNT_CAPABILITY_REFRESH_KEY",
"ACCOUNT_SUPPLY_REPLENISHMENT_KEY",
"ACCOUNT_SYNC_QUEUE_KEY",
"ACCOUNT_VALUE_PROJECTION_KEY",
"CK_HEALTH_KEY",
"CK_RELOGIN_KEY",
"DOUYU_TASKS_RETENTION_KEY",
@@ -75,6 +82,7 @@ __all__ = [
"run_account_capability_refresh",
"run_account_supply_replenishment",
"run_account_sync_queue_job",
"run_account_value_projection",
"run_ck_health",
"run_ck_relogin",
"run_douyu_tasks_retention",
@@ -114,6 +122,18 @@ def register_default_jobs() -> None:
default_enabled=True,
)
)
register_job(
JobSpec(
key=ACCOUNT_VALUE_PROJECTION_KEY,
title="账号价值投影刷新",
interval_seconds=10 * 60,
run_interval_seconds=10 * 60,
batch_size=1000,
concurrency=1,
run=run_account_value_projection,
default_enabled=True,
)
)
register_job(
JobSpec(
key=ACCOUNT_CAPABILITY_REFRESH_KEY,
@@ -7,7 +7,10 @@ from typing import Any
from sqlalchemy.orm import Session
from ....models import AutomationJob
from ...account_supply_service import enqueue_supply_replenishment
from ...account_supply_service import (
enqueue_supply_replenishment,
refresh_supply_snapshots,
)
JOB_KEY = "account_supply_replenishment"
@@ -16,6 +19,7 @@ def run_account_supply_replenishment(
db: Session,
job: AutomationJob,
) -> dict[str, Any]:
snapshots = refresh_supply_snapshots(db)
result = enqueue_supply_replenishment(
db,
max_per_target=max(1, int(job.batch_size or 50)),
@@ -34,6 +38,7 @@ def run_account_supply_replenishment(
"detail": {
"shortages": result.shortages,
"queued": result.queued,
"snapshots": len(snapshots),
},
}
@@ -0,0 +1,32 @@
"""低频刷新账号价值投影。"""
from __future__ import annotations
from typing import Any
from sqlalchemy.orm import Session
from ....models import AutomationJob
from ...account_value import refresh_account_value_tiers
JOB_KEY = "account_value_projection"
def run_account_value_projection(
db: Session,
job: AutomationJob,
) -> dict[str, Any]:
changed = refresh_account_value_tiers(
db,
batch_size=max(100, min(int(job.batch_size or 1000), 5000)),
)
return {
"scanned": changed,
"success": changed,
"invalid": 0,
"skipped": 0,
"message": f"刷新账号价值投影 {changed} 条",
}
__all__ = ["JOB_KEY", "run_account_value_projection"]
@@ -25,6 +25,7 @@ from sqlalchemy.orm import Session
from ....database import WorkerSessionLocal
from ....models import (
Account,
AccountWorkItem,
AutomationJob,
LoginAttempt,
LoginQuotaSetting,
@@ -46,6 +47,8 @@ from ...account_protection_service import (
from ...account_query_filters import automation_account_filter
from ...account_value import value_tier_expr
from ...account_work_queue import (
WORK_AGING_SECONDS,
active_account_work_exists,
claim_account_work,
enqueue_account_work,
fail_account_work_type,
@@ -80,6 +83,7 @@ DEFAULT_ADAPTIVE_MIN_SAMPLE = 10
DEFAULT_ADAPTIVE_GROW_RATE = 90.0
DEFAULT_ADAPTIVE_SHRINK_RATE = 70.0
DEFAULT_ADAPTIVE_GROW_FACTOR = 1.25
DEFAULT_ADAPTIVE_MAX_BATCH_SIZE = 20
@dataclass(frozen=True)
@@ -106,6 +110,7 @@ def build_select_query(
system_user_id: int | None = None,
batch_limit: int | None = None,
protection: ProtectionSnapshot | None = None,
apply_limit: bool = True,
):
"""构造本轮重登候选的查询(与取行分开,便于按方言编译做回归)。
@@ -117,31 +122,15 @@ def build_select_query(
``cookie_operable_filter`` 的 NOT EXISTS 子查询完成,走迁移 0042 新增的
``(account_id, attempt_status)`` 索引。
"""
query = (
db.query(Account)
.filter(Account.ck_check_status == "invalid")
.filter(automation_account_filter())
# 停用/归档的账号一律不碰(生命周期状态机,见 account_lifecycle)。
.filter(Account.relogin_attempts < max_attempts)
.filter(
or_(
Account.relogin_next_at.is_(None),
Account.relogin_next_at <= _cutoff(now),
)
)
)
# 已判定需要人工的类型不再自动重试(极验/凭证)。空值用 coalesce 兜住历史值。
query = query.filter(
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
)
)
snapshot = protection or load_protection_snapshot(db)
suppressed_ids = snapshot.suppressed_relogin_ids
if suppressed_ids:
# 保护组可以分别关闭自动重登。账号同时属于任一已开启自动重登的组时,
# 仍按允许处理;只有完全被抑制的账号才排除。
query = query.filter(~Account.id.in_(suppressed_ids))
query = _eligible_account_query(
db,
now,
max_attempts=max_attempts,
protection=snapshot,
cookie_operable=True,
due_only=True,
)
relogin_ids = snapshot.relogin_ids
if system_user_id is not None:
pass # 预留:将来若需要限制到某个归属人,在这里加过滤
@@ -162,7 +151,208 @@ def build_select_query(
1 if relogin_ids else 0,
value_tier_expr().asc(),
)
return query.order_by(*ordering).limit(max(limit, 1))
query = query.order_by(*ordering)
return query.limit(max(limit, 1)) if apply_limit else query
def _eligible_account_query(
db: Session,
now: datetime,
*,
max_attempts: int,
protection: ProtectionSnapshot,
cookie_operable: bool,
due_only: bool,
):
"""自动重登的账号级准入条件,执行、补货和计数共用同一套语义。"""
query = (
db.query(Account)
.filter(Account.ck_check_status == "invalid")
.filter(
automation_account_filter(cookie_operable=cookie_operable)
)
# 停用/归档的账号一律不碰(生命周期状态机,见 account_lifecycle)。
.filter(Account.relogin_attempts < max_attempts)
# 已判定需要人工的类型不再自动重试。空值用 coalesce 兜住历史值。
.filter(
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
)
)
)
if due_only:
query = query.filter(
or_(
Account.relogin_next_at.is_(None),
Account.relogin_next_at <= _cutoff(now),
)
)
if protection.suppressed_relogin_ids:
# 保护组可以分别关闭自动重登。账号同时属于任一已开启自动重登的组时,
# 仍按允许处理;只有完全被抑制的账号才排除。
query = query.filter(
~Account.id.in_(protection.suppressed_relogin_ids)
)
return query
def _pending_relogin_work_count(
db: Session,
*,
now: datetime,
) -> int:
return int(
db.query(func.count(AccountWorkItem.id))
.filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.due_at <= now,
)
.scalar()
or 0
)
def _enqueue_due_relogin_work(
db: Session,
job: AutomationJob,
now: datetime,
*,
max_attempts: int,
protection: ProtectionSnapshot,
limit: int,
) -> int:
"""把已判定失效但尚未进入队列的账号补成持久工作项。"""
accounts = build_select_query(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
apply_limit=False,
).filter(
~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN)
).limit(max(1, limit)).all()
for account in accounts:
priority = 10 if int(account.id) in protection.relogin_ids else 30
enqueue_account_work(
db,
account_id=int(account.id),
work_type=WORK_LOGIN_RELOGIN,
priority=priority,
max_attempts=20,
due_at=now,
reason="CK 已判定失效,等待受预算控制的重登",
)
if accounts:
db.flush()
return len(accounts)
def _count_actionable_relogin_accounts(
db: Session,
*,
now: datetime,
max_attempts: int,
protection: ProtectionSnapshot,
due_only: bool,
) -> int:
return int(
_eligible_account_query(
db,
now,
max_attempts=max_attempts,
protection=protection,
cookie_operable=False,
due_only=due_only,
)
.with_entities(func.count(Account.id))
.scalar()
or 0
)
def _queued_actionable_relogin_count(
db: Session,
*,
now: datetime,
max_attempts: int,
protection: ProtectionSnapshot,
) -> int:
eligible_ids = _eligible_account_query(
db,
now,
max_attempts=max_attempts,
protection=protection,
cookie_operable=False,
due_only=False,
).with_entities(Account.id)
return int(
db.query(func.count(AccountWorkItem.id))
.filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.account_id.in_(eligible_ids),
)
.scalar()
or 0
)
def _claim_relogin_work(
db: Session,
job: AutomationJob,
now: datetime,
*,
max_attempts: int,
protection: ProtectionSnapshot,
limit: int,
) -> list[AccountWorkItem]:
"""从持久队列领取重登任务,而不是每轮重新从账号表直接选执行对象。"""
eligible_ids = build_select_query(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
apply_limit=False,
).with_entities(Account.id)
account_ids = [
int(account_id)
for (account_id,) in (
db.query(AccountWorkItem.account_id)
.filter(
AccountWorkItem.work_type == WORK_LOGIN_RELOGIN,
AccountWorkItem.status == "pending",
AccountWorkItem.due_at <= now,
AccountWorkItem.account_id.in_(eligible_ids),
)
.order_by(
case(
(
AccountWorkItem.due_at
<= now - timedelta(seconds=WORK_AGING_SECONDS),
0,
),
else_=1,
),
AccountWorkItem.priority.asc(),
AccountWorkItem.due_at.asc(),
AccountWorkItem.id.asc(),
)
.limit(max(1, limit))
.all()
)
]
if not account_ids:
return []
return claim_account_work(
db,
work_types=(WORK_LOGIN_RELOGIN,),
account_ids=tuple(account_ids),
limit=limit,
now=now,
)
def _load_batch_state(
@@ -241,22 +431,23 @@ def count_pending_relogin(db: Session, *, max_attempts: int = 2) -> int:
count 只会得到批次上限(页面上显示恒等于 10),完全看不出积压。这里也**不
按退避窗口过滤** —— 退避是「什么时候试」的细节,不影响「还有多少要处理」。
"""
now = datetime.now(UTC)
snapshot = load_protection_snapshot(db)
query = (
db.query(func.count(Account.id))
.filter(Account.ck_check_status == "invalid")
.filter(automation_account_filter(cookie_operable=False))
# 停用/归档不计入积压(它们不会被自动处理,显示出来只会误导)
.filter(Account.relogin_attempts < max_attempts)
.filter(
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
)
)
queued = _queued_actionable_relogin_count(
db,
now=now,
max_attempts=max_attempts,
protection=snapshot,
)
if queued:
return queued
return _count_actionable_relogin_accounts(
db,
now=now,
max_attempts=max_attempts,
protection=snapshot,
due_only=False,
)
if snapshot.suppressed_relogin_ids:
query = query.filter(~Account.id.in_(snapshot.suppressed_relogin_ids))
return int(query.scalar() or 0)
def _system_user_id(db: Session) -> int | None:
@@ -376,12 +567,22 @@ def resolve_adaptive_batch_size(
) -> AdaptiveBatchDecision:
"""Scale the effective relogin batch inside the operator-configured ceiling."""
config = dict(job.config or {})
configured_max = max(int(job.batch_size or 1), 1)
configured_batch_size = max(int(job.batch_size or 1), 1)
configured_max = max(
configured_batch_size,
int(
config.get(
"adaptive_max_batch_size",
DEFAULT_ADAPTIVE_MAX_BATCH_SIZE,
)
or DEFAULT_ADAPTIVE_MAX_BATCH_SIZE
),
)
if not bool(config.get("adaptive_batch_enabled", True)):
decision = AdaptiveBatchDecision(
batch_size=configured_max,
batch_size=configured_batch_size,
configured_max=configured_max,
previous_batch_size=configured_max,
previous_batch_size=configured_batch_size,
success_rate=0.0,
sample_size=0,
pending=max(0, int(pending)),
@@ -479,56 +680,61 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
"message": "库里没有可用用户,无法以系统身份发起重登",
}
pending = count_pending_relogin(db, max_attempts=max_attempts)
protection = load_protection_snapshot(db)
queued_due = _pending_relogin_work_count(db, now=now)
actionable = _count_actionable_relogin_accounts(
db,
now=now,
max_attempts=max_attempts,
protection=protection,
due_only=True,
)
pending = max(queued_due, actionable)
adaptive = resolve_adaptive_batch_size(
db,
job,
now=now,
pending=pending,
)
protection = load_protection_snapshot(db)
accounts = build_select_query(
work_items = _claim_relogin_work(
db,
job,
now,
max_attempts=max_attempts,
batch_limit=adaptive.batch_size,
protection=protection,
).all()
if not accounts:
db.commit()
return {"scanned": 0, "valid": 0, "invalid": 0, "skipped": 0}
selected_account_ids = tuple(int(account.id) for account in accounts)
for account in accounts:
priority = 10 if int(account.id) in protection.relogin_ids else 30
enqueue_account_work(
db,
account_id=int(account.id),
work_type=WORK_LOGIN_RELOGIN,
priority=priority,
max_attempts=20,
due_at=now,
reason="CK 失效,等待自动重登",
)
db.commit()
work_items = claim_account_work(
db,
work_types=(WORK_LOGIN_RELOGIN,),
account_ids=selected_account_ids,
limit=len(selected_account_ids),
now=now,
limit=adaptive.batch_size,
)
db.commit()
claimed_account_ids = [int(item.account_id) for item in work_items]
if not claimed_account_ids:
remaining = adaptive.batch_size - len(work_items)
if remaining > 0:
_enqueue_due_relogin_work(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
limit=remaining,
)
work_items.extend(
_claim_relogin_work(
db,
job,
now,
max_attempts=max_attempts,
protection=protection,
limit=remaining,
)
)
if not work_items:
db.commit()
return {
"scanned": 0,
"valid": 0,
"invalid": 0,
"skipped": len(selected_account_ids),
"message": "候选账号的重登工作项已被其他执行器领取",
"skipped": 0,
"message": "没有到期的自动重登工作项",
}
db.commit()
claimed_account_ids = [int(item.account_id) for item in work_items]
account_map = {
int(account.id): account
for account in db.query(Account)
@@ -721,12 +927,13 @@ def settle_results(
if kind == "email_quota":
counters["email_quota"] += 1
counters["retry"] += 1
account.relogin_next_at = _next_retry_at(kind, account.relogin_attempts, now)
next_retry_at = _next_retry_at(kind, account.relogin_attempts, now)
account.relogin_next_at = next_retry_at
reschedule_account_work_type(
db,
account_id=int(account.id),
work_type=WORK_LOGIN_RELOGIN,
due_at=account.relogin_next_at,
due_at=next_retry_at,
reason=f"自动重登未成功({kind}),按账号退避时间重试",
)
# 排了下一次重试 → 仍是 invalid(不是 manual)
@@ -45,10 +45,10 @@ from datetime import UTC, datetime, timedelta
from typing import Any
from loguru import logger
from sqlalchemy import text
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session
from ....models import AutomationJob
from ....models import AutomationJob, DouyuTask
JOB_KEY = "douyu_tasks_retention"
@@ -106,40 +106,55 @@ def _delete_batch(
cutoff: datetime,
batch: int,
negate: bool = False,
) -> int:
"""删一批过期行,返回删除条数。
cursor_created_at: datetime | None = None,
cursor_id: int = 0,
) -> tuple[int, datetime | None, int]:
"""按时间/主键游标取一批过期 ID,删除后返回新游标。
`negate=True` 时语义变成「**除这些类型之外**的都在这一档」—— 长保留档就是这么
表达的。这样做有个重要的安全属性:**新增的任务类型默认落在长保留档**,
不会因为「忘了往某个列表里加」而在 7 天后被误删(收集器当年就是反过来,
忘了加 allowlist 就静默丢数据)。
`LIMIT` 让单条语句不会长时间持锁。
先取有限 ID 再按主键删除,单条语句不会长时间持锁;游标保证跨批次只向前扫。
"""
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 0, cursor_created_at, cursor_id
type_filter = (
~DouyuTask.task_type.in_(task_types)
if negate
else DouyuTask.task_type.in_(task_types)
)
return int(result.rowcount or 0)
query = db.query(DouyuTask.id, DouyuTask.created_at).filter(
type_filter,
~DouyuTask.status.in_(IN_FLIGHT_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]:
@@ -167,13 +182,17 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]
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 = _delete_batch(
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