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
+15 -3
View File
@@ -12,6 +12,8 @@ from ..models import (
Account,
AccountCommodityState,
AccountEvent,
AccountSupplySnapshot,
AccountSupplyTarget,
AccountSyncRun,
AccountSyncState,
AccountWorkItem,
@@ -19,7 +21,7 @@ from ..models import (
)
from .account_capability_service import AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED
from .account_protection_service import evaluate_protection_targets
from .account_supply_service import evaluate_supply_targets
from .account_supply_service import load_supply_snapshot_inventories
TREND_DAYS = 7
@@ -265,7 +267,7 @@ def _supply_snapshot(
db: Session,
moment: datetime,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
inventories = evaluate_supply_targets(db, now=moment)
inventories = load_supply_snapshot_inventories(db, now=moment)
supply_targets: list[dict[str, Any]] = []
alerts: list[dict[str, Any]] = []
for item in inventories:
@@ -331,8 +333,18 @@ def account_supply_snapshot(
"""返回可延迟加载的账号供给库存,避免阻塞运行总览首屏。"""
moment = now or datetime.now(UTC)
supply_targets, alerts = _supply_snapshot(db, moment)
checked_at = (
db.query(func.max(AccountSupplySnapshot.checked_at))
.join(
AccountSupplyTarget,
AccountSupplyTarget.id == AccountSupplySnapshot.target_id,
)
.filter(AccountSupplyTarget.enabled.is_(True))
.scalar()
or moment
)
return {
"checked_at": moment,
"checked_at": checked_at,
"supply_targets": supply_targets,
"alerts": alerts,
}
+123 -2
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import os
from dataclasses import dataclass
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from sqlalchemy import and_, case, func, select
from sqlalchemy.exc import IntegrityError
@@ -13,6 +13,7 @@ from sqlalchemy.orm import Session
from ..models import (
Account,
AccountCommodityState,
AccountSupplySnapshot,
AccountSupplyTarget,
AccountSyncState,
)
@@ -58,6 +59,7 @@ DEFAULT_SUPPLY_TARGETS = (
"safety_buffer": 60,
},
)
DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS = 15 * 60
@dataclass(frozen=True)
@@ -364,6 +366,123 @@ def evaluate_supply_targets(
return inventories
def _enabled_supply_targets(db: Session) -> list[AccountSupplyTarget]:
return (
db.query(AccountSupplyTarget)
.filter(AccountSupplyTarget.enabled.is_(True))
.order_by(
AccountSupplyTarget.platform.asc(),
AccountSupplyTarget.scope.asc(),
AccountSupplyTarget.value_class.asc(),
AccountSupplyTarget.commodity_id.asc(),
)
.all()
)
def supply_snapshot_max_age_seconds() -> int:
raw = os.getenv(
"ACCOUNT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS",
str(DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS),
)
try:
return max(30, int(raw))
except ValueError:
return DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS
def refresh_supply_snapshots(
db: Session,
*,
now: datetime | None = None,
) -> list[SupplyInventory]:
"""重算并持久化供给快照;只由后台作业或明确的回源路径调用。"""
moment = now or datetime.now(UTC)
inventories = evaluate_supply_targets(db, now=moment)
existing = {
int(row.target_id): row
for row in db.query(AccountSupplySnapshot)
.filter(
AccountSupplySnapshot.target_id.in_(
[item.target_id for item in inventories]
)
)
.all()
} if inventories else {}
for inventory in inventories:
row = existing.get(inventory.target_id)
if row is None:
row = AccountSupplySnapshot(
target_id=inventory.target_id,
covered=inventory.covered,
available=inventory.available,
allocatable=inventory.allocatable,
checked_at=moment,
)
try:
with db.begin_nested():
db.add(row)
db.flush()
except IntegrityError:
row = (
db.query(AccountSupplySnapshot)
.filter(
AccountSupplySnapshot.target_id
== inventory.target_id
)
.one()
)
row.covered = inventory.covered
row.available = inventory.available
row.allocatable = inventory.allocatable
row.checked_at = moment
row.updated_at = moment
if inventories:
db.commit()
return inventories
def load_supply_snapshot_inventories(
db: Session,
*,
now: datetime | None = None,
refresh_if_stale: bool = True,
) -> list[SupplyInventory]:
"""优先读快照;缺失或超过有效期时回源一次并刷新快照。"""
moment = now or datetime.now(UTC)
targets = _enabled_supply_targets(db)
if not targets:
return []
snapshots = {
int(row.target_id): row
for row in db.query(AccountSupplySnapshot)
.filter(
AccountSupplySnapshot.target_id.in_(
[int(target.id) for target in targets]
)
)
.all()
}
fresh_after = moment - timedelta(seconds=supply_snapshot_max_age_seconds())
if all(
int(target.id) in snapshots
and snapshots[int(target.id)].checked_at >= fresh_after
for target in targets
):
return [
_inventory_from_counts(
target,
covered=int(snapshots[int(target.id)].covered or 0),
available=int(snapshots[int(target.id)].available or 0),
allocatable=int(snapshots[int(target.id)].allocatable or 0),
)
for target in targets
]
if refresh_if_stale:
return refresh_supply_snapshots(db, now=moment)
return evaluate_supply_targets(db, now=moment)
def upsert_supply_target(
db: Session,
*,
@@ -569,7 +688,7 @@ def enqueue_supply_replenishment(
) -> SupplyReplenishmentResult:
"""按本地目标缺口定向入队 storehome 同步,不发起外部请求。"""
moment = now or datetime.now(UTC)
inventories = evaluate_supply_targets(db, now=moment)
inventories = load_supply_snapshot_inventories(db, now=moment)
queued = 0
shortages = 0
pending = active_account_work_count(
@@ -633,6 +752,8 @@ __all__ = [
"ensure_default_supply_targets",
"evaluate_supply_target",
"evaluate_supply_targets",
"load_supply_snapshot_inventories",
"refresh_supply_snapshots",
"update_supply_target",
"upsert_supply_target",
]
+53 -2
View File
@@ -19,6 +19,7 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
from sqlalchemy import and_, case, or_
from sqlalchemy.orm import Session
from ..models import Account
from .high_value_service import (
@@ -134,8 +135,8 @@ def high_value_needs_refresh_expr(
)
def value_tier_expr(*, now: datetime | None = None):
"""1–5 档。没查过、也没有任何资产信号时落在第 5 档。"""
def _computed_value_tier_expr(*, now: datetime | None = None):
"""实时计算 1–5 档,仅用于投影回填和冷启动回退。"""
available_bairimeng = suit_available_expr("bairimeng", now=now)
available_mengtu = suit_available_expr("mengtu", now=now)
both_available = and_(available_bairimeng, available_mengtu)
@@ -152,6 +153,14 @@ def value_tier_expr(*, now: datetime | None = None):
)
def value_tier_expr(*, now: datetime | None = None):
"""优先读后台投影;投影缺失时回退实时计算,保证灰度期行为不变。"""
return case(
(Account.value_tier.isnot(None), Account.value_tier),
else_=_computed_value_tier_expr(now=now),
)
def is_high_value_expr(*, now: datetime | None = None):
"""第 1、2 档:巡检加密、重登插队、列表「高价值待救」都用这一条。"""
return value_tier_expr(now=now) <= HIGH_VALUE_TIER_MAX
@@ -175,6 +184,48 @@ def is_high_value_account(
return available or int(account.points or 0) >= HIGH_VALUE_POINTS
def refresh_account_value_tiers(
db: Session,
*,
now: datetime | None = None,
batch_size: int = 1000,
) -> int:
"""分批刷新账号价值投影,避免在页面请求里反复执行大 CASE。"""
moment = now or datetime.now(UTC)
batch = max(1, int(batch_size))
last_id = 0
changed = 0
while True:
account_ids = [
int(row[0])
for row in (
db.query(Account.id)
.filter(Account.id > last_id)
.order_by(Account.id.asc())
.limit(batch)
.all()
)
]
if not account_ids:
break
tier = _computed_value_tier_expr(now=moment)
changed += int(
db.query(Account)
.filter(
Account.id.in_(account_ids),
or_(
Account.value_tier.is_(None),
Account.value_tier != tier,
),
)
.update({Account.value_tier: tier}, synchronize_session=False)
or 0
)
db.commit()
last_id = account_ids[-1]
return changed
def suit_sort_rank_expr(*, now: datetime | None = None):
"""列表「高价值套装」列的排序,和格子上看到的一致。数字越小越值钱。
+13 -1
View File
@@ -5,12 +5,14 @@ from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import func, select
from sqlalchemy import case, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ..models import Account, AccountWorkItem
WORK_AGING_SECONDS = 30 * 60
def active_account_work_exists(*, work_type: str):
"""SQL 子查询:同一账号已有同类型的待执行或运行中工作。"""
@@ -121,6 +123,16 @@ def claim_account_work(
rows = (
query
.order_by(
# 到期超过 30 分钟的工作优先出队,避免固定业务优先级造成永久饥饿。
# due_at 是工作项真正可执行的起点;未来重试项不会命中这个分支。
case(
(
AccountWorkItem.due_at
<= moment - timedelta(seconds=WORK_AGING_SECONDS),
0,
),
else_=1,
),
AccountWorkItem.priority.asc(),
AccountWorkItem.due_at.asc(),
AccountWorkItem.id.asc(),
@@ -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
@@ -43,6 +43,10 @@ def _load_task_for_update(db: Session, task_id: int) -> PlatformFulfillmentTask:
)
if task is None:
raise HTTPException(status_code=404, detail="直播账号履约任务不存在")
from .views import invalidate_task_list_count_cache
# 所有用户操作写路径都会先拿行锁;在这里失效可覆盖完成、取消、恢复等状态变更。
invalidate_task_list_count_cache()
return task
@@ -2,6 +2,10 @@
from __future__ import annotations
import threading
import time
import weakref
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
@@ -40,6 +44,159 @@ from .common import (
)
from .repository import _load_task
_TASK_COUNT_CACHE_TTL_SECONDS = 15.0
_TASK_COUNT_CACHE_MAX_ENTRIES = 512
_TASK_COUNT_CACHE: weakref.WeakKeyDictionary[
Any, dict[tuple[Any, ...], tuple[float, int]]
] = weakref.WeakKeyDictionary()
_TASK_COUNT_CACHE_LOCK = threading.Lock()
@dataclass
class _TaskOutputContext:
mappings: dict[int, PlatformCommodityMapping]
goods: dict[str, DouyuGoodsSnapshot]
accounts: dict[int, Account]
leases: dict[int, AccountLease]
bind_tasks: dict[int, DouyuTask]
collab_orders: dict[int, DouyuExternalOrder]
def invalidate_task_list_count_cache() -> None:
"""任务写入后清空分页总数缓存,最多 15 秒的跨进程陈旧由 TTL 兜底。"""
with _TASK_COUNT_CACHE_LOCK:
_TASK_COUNT_CACHE.clear()
def _count_cache_key(
*,
cutoff: datetime | None,
status: str,
queue_bucket: str,
sale_mode: str,
keyword: str,
) -> tuple[Any, ...]:
return (
cutoff,
status,
queue_bucket,
sale_mode,
keyword.strip(),
)
def _cached_task_count(
db: Session,
query,
*,
key: tuple[Any, ...],
) -> int:
moment = time.monotonic()
bind = db.get_bind()
with _TASK_COUNT_CACHE_LOCK:
engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {})
cached = engine_cache.get(key)
if cached and moment - cached[0] < _TASK_COUNT_CACHE_TTL_SECONDS:
return cached[1]
total = int(query.count())
with _TASK_COUNT_CACHE_LOCK:
engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {})
if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES:
expired_before = moment - _TASK_COUNT_CACHE_TTL_SECONDS
for cache_key, (cached_at, _) in list(engine_cache.items()):
if cached_at < expired_before:
engine_cache.pop(cache_key, None)
if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES:
engine_cache.pop(next(iter(engine_cache)), None)
engine_cache[key] = (moment, total)
return total
def _load_task_output_context(
db: Session,
tasks: list[PlatformFulfillmentTask],
) -> _TaskOutputContext:
mapping_ids = {
int(task.commodity_mapping_id)
for task in tasks
if task.commodity_mapping_id
}
commodity_ids = {
str(task.commodity_id)
for task in tasks
if task.commodity_id
}
account_ids = {int(task.account_id) for task in tasks if task.account_id}
lease_ids = {int(task.lease_id) for task in tasks if task.lease_id}
bind_task_ids = {int(task.bind_task_id) for task in tasks if task.bind_task_id}
task_ids = {int(task.id) for task in tasks}
mappings = (
{
int(row.id): row
for row in db.query(PlatformCommodityMapping)
.filter(PlatformCommodityMapping.id.in_(mapping_ids))
.all()
}
if mapping_ids
else {}
)
goods: dict[str, DouyuGoodsSnapshot] = {}
if commodity_ids:
for row in (
db.query(DouyuGoodsSnapshot)
.filter(DouyuGoodsSnapshot.commodity_id.in_(commodity_ids))
.order_by(DouyuGoodsSnapshot.id.desc())
.all()
):
goods.setdefault(str(row.commodity_id), row)
accounts = (
{
int(row.id): row
for row in db.query(Account).filter(Account.id.in_(account_ids)).all()
}
if account_ids
else {}
)
leases = (
{
int(row.id): row
for row in db.query(AccountLease)
.filter(AccountLease.id.in_(lease_ids))
.all()
}
if lease_ids
else {}
)
bind_tasks = (
{
int(row.id): row
for row in db.query(DouyuTask)
.filter(DouyuTask.id.in_(bind_task_ids))
.all()
}
if bind_task_ids
else {}
)
collab_orders: dict[int, DouyuExternalOrder] = {}
if task_ids:
for row in (
db.query(DouyuExternalOrder)
.filter(DouyuExternalOrder.source_task_id.in_(task_ids))
.order_by(DouyuExternalOrder.id.desc())
.all()
):
if row.source_task_id is not None:
collab_orders.setdefault(int(row.source_task_id), row)
return _TaskOutputContext(
mappings=mappings,
goods=goods,
accounts=accounts,
leases=leases,
bind_tasks=bind_tasks,
collab_orders=collab_orders,
)
def list_tasks(
db: Session,
@@ -51,8 +208,9 @@ def list_tasks(
page: int = 1,
page_size: int = 20,
) -> dict[str, Any]:
cutoff = _order_match_started_at(db)
query = db.query(PlatformFulfillmentTask)
query = _apply_order_match_cutoff(query, _order_match_started_at(db))
query = _apply_order_match_cutoff(query, cutoff)
query = query.filter(
or_(
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
@@ -137,7 +295,17 @@ def list_tasks(
Account.uid.ilike(pattern),
)
)
total = query.count()
total = _cached_task_count(
db,
query,
key=_count_cache_key(
cutoff=cutoff,
status=status,
queue_bucket=queue_bucket,
sale_mode=sale_mode,
keyword=keyword,
),
)
rows = (
query.order_by(
PlatformFulfillmentTask.paid_at.desc(),
@@ -147,8 +315,9 @@ def list_tasks(
.limit(max(1, min(page_size, 100)))
.all()
)
context = _load_task_output_context(db, rows)
return {
"items": [_task_out(db, row) for row in rows],
"items": [_task_out(db, row, context=context) for row in rows],
"pagination": {
"page": max(1, page),
"pageSize": max(1, page_size),
@@ -163,19 +332,16 @@ def _task_out(
*,
include_qr: bool = False,
include_exchange_task: bool = False,
context: _TaskOutputContext | None = None,
) -> dict[str, Any]:
resolved = context or _load_task_output_context(db, [task])
mapping = (
db.query(PlatformCommodityMapping)
.filter(PlatformCommodityMapping.id == task.commodity_mapping_id)
.first()
resolved.mappings.get(int(task.commodity_mapping_id))
if task.commodity_mapping_id
else None
)
goods = (
db.query(DouyuGoodsSnapshot)
.filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id)
.order_by(DouyuGoodsSnapshot.id.desc())
.first()
resolved.goods.get(str(task.commodity_id))
if task.commodity_id
else None
)
@@ -186,25 +352,15 @@ def _task_out(
or task.internal_sku_key
)
account = (
db.query(Account).filter(Account.id == task.account_id).first()
if task.account_id
else None
)
lease = (
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if task.lease_id
else None
resolved.accounts.get(int(task.account_id)) if task.account_id else None
)
lease = resolved.leases.get(int(task.lease_id)) if task.lease_id else None
bind_task = (
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
resolved.bind_tasks.get(int(task.bind_task_id))
if task.bind_task_id
else None
)
collab_order = (
db.query(DouyuExternalOrder)
.filter(DouyuExternalOrder.source_task_id == task.id)
.first()
)
collab_order = resolved.collab_orders.get(int(task.id))
bind_result = (bind_task.result or {}) if bind_task else {}
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
effective_last_error = _effective_task_message(task, effective_issue)