fix(fulfillment): 主动补全有效 CK 商品能力缓存

This commit is contained in:
yml
2026-11-28 20:53:25 +08:00
parent c8efa6d808
commit 7ca011c14e
14 changed files with 296 additions and 69 deletions
+3 -1
View File
@@ -124,7 +124,9 @@ def register_default_jobs() -> None:
title="账号内部同步队列",
interval_seconds=60,
run_interval_seconds=60,
batch_size=20,
# 有效 CK 的 storehome 快照默认 6 小时过期;1 万多个账号需要
# 至少约 30 条/分钟才能在一个 TTL 周期内补完,留出 40 条余量。
batch_size=40,
concurrency=3,
run=run_account_sync_queue_job,
default_enabled=True,
@@ -1,6 +1,8 @@
"""按直播履约需求把过期商品能力账号送入内部同步队列。
"""把待履约和全库过期的商品能力账号送入内部同步队列。
本作业只做本地候选筛选,不直接请求官网。真正的 ``storehome`` 查询由
优先处理 pending 履约商品,再用剩余水位补全所有 CK 有效但缺少新鲜
``storehome`` 快照的账号。本作业只做本地候选筛选,不直接请求官网。
真正的 ``storehome`` 查询由
``account_sync_queue`` 作业在独立执行槽中低并发消费,避免补货查询抢占
履约实时复核、登录或批量任务的执行资源。
"""
@@ -27,6 +29,7 @@ from ...account_work_queue import (
)
from ...platform_fulfillment.account_selector import (
capability_refresh_candidate_accounts,
storehome_refresh_candidate_accounts,
)
JOB_KEY = "account_capability_refresh"
@@ -37,18 +40,15 @@ def _pending_demand_rows(
now: datetime,
) -> list[tuple[str, int]]:
"""返回待分配商品及订单数,按缺口大小排序。"""
pending_commodities_query = (
select(
PlatformFulfillmentTask.commodity_id,
func.count(PlatformFulfillmentTask.id).label("waiting"),
)
.where(
PlatformFulfillmentTask.execution_status == "ready",
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.commodity_id != "",
PlatformFulfillmentTask.target_platform == "douyu",
PlatformFulfillmentTask.scope == "elite",
)
pending_commodities_query = select(
PlatformFulfillmentTask.commodity_id,
func.count(PlatformFulfillmentTask.id).label("waiting"),
).where(
PlatformFulfillmentTask.execution_status == "ready",
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.commodity_id != "",
PlatformFulfillmentTask.target_platform == "douyu",
PlatformFulfillmentTask.scope == "elite",
)
match_started_at = (
db.query(PlatformFulfillmentSetting.order_match_started_at)
@@ -59,12 +59,13 @@ def _pending_demand_rows(
pending_commodities_query = pending_commodities_query.where(
PlatformFulfillmentTask.paid_at >= match_started_at
)
statement = (
pending_commodities_query
.group_by(PlatformFulfillmentTask.commodity_id)
.order_by(func.count(PlatformFulfillmentTask.id).desc())
)
return list(db.execute(statement).all())
statement = pending_commodities_query.group_by(
PlatformFulfillmentTask.commodity_id
).order_by(func.count(PlatformFulfillmentTask.id).desc())
return [
(str(commodity_id), int(waiting))
for commodity_id, waiting in db.execute(statement).all()
]
def _order_queue_target_pending() -> int:
@@ -88,27 +89,15 @@ def _build_select_query(
batch_limit: int | None = None,
):
moment = now or datetime.now(UTC)
demand_rows = _pending_demand_rows(db, moment)
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
if not commodity_ids:
return db.query(Account).filter(Account.id == -1)
batch = max(
1,
min(
int(batch_limit if batch_limit is not None else job.batch_size or 100),
100,
),
)
candidates = capability_refresh_candidate_accounts(
accounts, _, _ = _refresh_candidates(
db,
commodity_ids=commodity_ids,
scope="elite",
limit=batch,
now=moment,
job,
moment,
batch_limit=batch_limit,
)
if not candidates:
if not accounts:
return db.query(Account).filter(Account.id == -1)
rank = {int(account.id): index for index, account in enumerate(candidates)}
rank = {int(account.id): index for index, account in enumerate(accounts)}
return (
db.query(Account)
.filter(Account.id.in_(tuple(rank)))
@@ -119,6 +108,50 @@ def _build_select_query(
)
def _refresh_candidates(
db: Session,
job: AutomationJob,
moment: datetime,
*,
batch_limit: int | None = None,
) -> tuple[list[Account], set[int], list[str]]:
"""先补待履约商品,再用剩余水位补全其他 CK 有效账号。"""
demand_rows = _pending_demand_rows(db, moment)
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
batch = max(
1,
min(
int(batch_limit if batch_limit is not None else job.batch_size or 100),
100,
),
)
demand_candidates = (
capability_refresh_candidate_accounts(
db,
commodity_ids=commodity_ids,
scope="elite",
limit=batch,
now=moment,
)
if commodity_ids
else []
)
demand_ids = {int(account.id) for account in demand_candidates}
remaining = batch - len(demand_candidates)
backfill_candidates = (
storehome_refresh_candidate_accounts(
db,
limit=remaining,
now=moment,
exclude_account_ids=tuple(demand_ids),
)
if remaining > 0
else []
)
accounts = [*demand_candidates, *backfill_candidates]
return accounts, demand_ids, commodity_ids
def build_select_query(
db: Session,
job: AutomationJob,
@@ -150,23 +183,23 @@ def run_account_capability_refresh(
),
"detail": {"queued": 0, "pending": pending, "headroom": 0},
}
demand_rows = _pending_demand_rows(db, now)
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
accounts = _build_select_query(
accounts, demand_ids, commodity_ids = _refresh_candidates(
db,
job,
now,
batch_limit=headroom,
).all()
)
for account in accounts:
is_demand_refresh = int(account.id) in demand_ids
enqueue_account_work(
db,
account_id=int(account.id),
work_type=WORK_STOREHOME_SYNC,
priority=10,
priority=10 if is_demand_refresh else 30,
reason=(
"待履约商品补货: "
+ ",".join(commodity_ids[:5])
("待履约商品补货: " + ",".join(commodity_ids[:5]))
if is_demand_refresh and commodity_ids
else "账号商品能力补全"
)[:255],
due_at=now,
)
@@ -178,9 +211,9 @@ def run_account_capability_refresh(
"invalid": 0,
"skipped": 0,
"message": (
f"本轮筛选 {len(accounts)} 个待补货账号,新入队 {queued} 个"
f"本轮筛选 {len(accounts)} 个需刷新能力账号,新入队 {queued} 个"
if accounts
else "当前履约商品没有可补充的新鲜 CK 候选账号"
else "没有需要补全商品能力缓存的 CK 有效账号"
),
"detail": {
"queued": queued,
@@ -188,6 +221,8 @@ def run_account_capability_refresh(
"order_cap": _order_queue_target_pending(),
"headroom": headroom,
"commodities": commodity_ids[:20],
"demand_refresh": len(demand_ids),
"backfill_refresh": max(0, queued - len(demand_ids)),
},
}
@@ -623,6 +623,18 @@ def capability_candidate_accounts(
]
def _refresh_candidate_order_by(now: datetime) -> tuple[Any, ...]:
return (
case((active_lease_exists(), 1), else_=0),
case((active_collab_order_exists(), 1), else_=0),
case((role_change_ready_filter(now), 0), else_=1),
case((Account.role_bind_status == "unbound", 0), else_=1),
Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(),
Account.id.asc(),
)
def capability_refresh_candidate_accounts(
db: Session,
*,
@@ -699,15 +711,52 @@ def capability_refresh_candidate_accounts(
assigned_to_pool_filter(),
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
)
.order_by(
case((active_lease_exists(), 1), else_=0),
case((active_collab_order_exists(), 1), else_=0),
case((role_change_ready_filter(moment), 0), else_=1),
case((Account.role_bind_status == "unbound", 0), else_=1),
Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(),
Account.id.asc(),
.order_by(*_refresh_candidate_order_by(moment))
.limit(max(1, min(int(limit), 100)))
.all()
)
def storehome_refresh_candidate_accounts(
db: Session,
*,
limit: int = 20,
now: datetime | None = None,
exclude_account_ids: tuple[int, ...] | list[int] = (),
) -> list[Account]:
"""选择 CK 有效但缺少新鲜 storehome 快照的账号做全量能力补全。
能力缓存过期不等于 CK 失效。只要 CK 结论仍为有效且账号可自动操作,
就可以重新查询 storehome 并把整个商品能力目录写回本地。
"""
moment = _now(now)
fresh_storehome = (
select(AccountSyncState.id)
.where(
AccountSyncState.account_id == Account.id,
AccountSyncState.platform == "douyu",
AccountSyncState.domain == "storehome",
AccountSyncState.status == "success",
AccountSyncState.valid_until.isnot(None),
AccountSyncState.valid_until > moment,
)
.exists()
)
excluded_ids = tuple(
dict.fromkeys(int(account_id) for account_id in exclude_account_ids)
)
query = db.query(Account).filter(
~fresh_storehome,
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
)
if excluded_ids:
query = query.filter(~Account.id.in_(excluded_ids))
return (
query.order_by(*_refresh_candidate_order_by(moment))
.limit(max(1, min(int(limit), 100)))
.all()
)
@@ -969,4 +1018,5 @@ __all__ = [
"live_candidate_accounts",
"release_lease",
"renew_lease",
"storehome_refresh_candidate_accounts",
]