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
+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):
"""列表「高价值套装」列的排序,和格子上看到的一致。数字越小越值钱。