268 lines
7.9 KiB
Python
268 lines
7.9 KiB
Python
"""把待履约和全库过期的商品能力账号送入内部同步队列。
|
|
|
|
优先处理 pending 履约商品,再用剩余水位补全所有 CK 有效但缺少新鲜
|
|
``storehome`` 快照的账号。本作业只做本地候选筛选,不直接请求官网。
|
|
真正的 ``storehome`` 查询由
|
|
``account_sync_queue`` 作业在独立执行槽中低并发消费,避免补货查询抢占
|
|
履约实时复核、登录或批量任务的执行资源。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
|
|
from sqlalchemy import case, func, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ....models import (
|
|
Account,
|
|
AutomationJob,
|
|
PlatformFulfillmentSetting,
|
|
PlatformFulfillmentTask,
|
|
)
|
|
from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
|
|
from ...account_work_queue import (
|
|
SUPPLY_REASON_PREFIX,
|
|
active_account_work_count,
|
|
enqueue_account_work,
|
|
)
|
|
from ...platform_fulfillment.account_selector import (
|
|
capability_refresh_candidate_accounts,
|
|
storehome_refresh_candidate_accounts,
|
|
)
|
|
from ...platform_fulfillment.policy import (
|
|
bundle_requirements_for_commodity,
|
|
normalize_allocation_policy,
|
|
)
|
|
|
|
JOB_KEY = "account_capability_refresh"
|
|
DEFAULT_BACKFILL_RESERVED_SLOTS = 8
|
|
|
|
|
|
def _pending_demand_rows(
|
|
db: Session,
|
|
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",
|
|
)
|
|
match_started_at = (
|
|
db.query(PlatformFulfillmentSetting.order_match_started_at)
|
|
.filter(PlatformFulfillmentSetting.id == 1)
|
|
.scalar()
|
|
)
|
|
if match_started_at is not None:
|
|
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 [
|
|
(str(commodity_id), int(waiting))
|
|
for commodity_id, waiting in db.execute(statement).all()
|
|
]
|
|
|
|
|
|
def _order_queue_target_pending() -> int:
|
|
"""订单能力补货自己的水位;通用供给有自己的保留水位。"""
|
|
import os
|
|
|
|
raw = os.getenv("ACCOUNT_ORDER_QUEUE_TARGET_PENDING")
|
|
if raw is None:
|
|
raw = os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "70")
|
|
try:
|
|
return max(1, int(raw))
|
|
except ValueError:
|
|
return 70
|
|
|
|
|
|
def _backfill_reserved_slots() -> int:
|
|
import os
|
|
|
|
raw = os.getenv(
|
|
"ACCOUNT_CAPABILITY_BACKFILL_RESERVED_SLOTS",
|
|
str(DEFAULT_BACKFILL_RESERVED_SLOTS),
|
|
)
|
|
try:
|
|
return max(0, min(int(raw), 100))
|
|
except ValueError:
|
|
return DEFAULT_BACKFILL_RESERVED_SLOTS
|
|
|
|
|
|
def _preferred_bundle_groups(
|
|
db: Session,
|
|
commodity_ids: list[str],
|
|
) -> tuple[tuple[str, ...], ...]:
|
|
if not commodity_ids:
|
|
return ()
|
|
row = db.get(PlatformFulfillmentSetting, 1)
|
|
policy = normalize_allocation_policy(
|
|
row.allocation_policy_json if row is not None else None
|
|
)
|
|
groups: list[tuple[str, ...]] = []
|
|
for commodity_id in commodity_ids:
|
|
required, _ = bundle_requirements_for_commodity(policy, commodity_id)
|
|
if not required:
|
|
continue
|
|
group = tuple(dict.fromkeys((commodity_id, *required)))
|
|
if group not in groups:
|
|
groups.append(group)
|
|
return tuple(groups)
|
|
|
|
|
|
def _build_select_query(
|
|
db: Session,
|
|
job: AutomationJob,
|
|
now: datetime | None = None,
|
|
*,
|
|
batch_limit: int | None = None,
|
|
):
|
|
moment = now or datetime.now(UTC)
|
|
accounts, _, _ = _refresh_candidates(
|
|
db,
|
|
job,
|
|
moment,
|
|
batch_limit=batch_limit,
|
|
)
|
|
if not accounts:
|
|
return db.query(Account).filter(Account.id == -1)
|
|
rank = {int(account.id): index for index, account in enumerate(accounts)}
|
|
return (
|
|
db.query(Account)
|
|
.filter(Account.id.in_(tuple(rank)))
|
|
.order_by(
|
|
case(rank, value=Account.id),
|
|
Account.id.asc(),
|
|
)
|
|
)
|
|
|
|
|
|
def _refresh_candidates(
|
|
db: Session,
|
|
job: AutomationJob,
|
|
moment: datetime,
|
|
*,
|
|
batch_limit: int | None = None,
|
|
backfill_floor: int = 0,
|
|
) -> 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(
|
|
0,
|
|
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 and batch > 0
|
|
else []
|
|
)
|
|
demand_ids = {int(account.id) for account in demand_candidates}
|
|
backfill_limit = max(backfill_floor, batch - len(demand_candidates))
|
|
backfill_candidates = (
|
|
storehome_refresh_candidate_accounts(
|
|
db,
|
|
limit=backfill_limit,
|
|
now=moment,
|
|
exclude_account_ids=tuple(demand_ids),
|
|
scope="elite",
|
|
preferred_commodity_groups=_preferred_bundle_groups(db, commodity_ids),
|
|
)
|
|
if backfill_limit > 0
|
|
else []
|
|
)
|
|
accounts = [*demand_candidates, *backfill_candidates]
|
|
return accounts, demand_ids, commodity_ids
|
|
|
|
|
|
def build_select_query(
|
|
db: Session,
|
|
job: AutomationJob,
|
|
now: datetime | None = None,
|
|
):
|
|
return _build_select_query(db, job, now)
|
|
|
|
|
|
def run_account_capability_refresh(
|
|
db: Session,
|
|
job: AutomationJob,
|
|
) -> dict[str, Any]:
|
|
now = datetime.now(UTC)
|
|
pending = active_account_work_count(
|
|
db,
|
|
work_types=ACCOUNT_SYNC_WORK_TYPES,
|
|
exclude_reason_prefix=SUPPLY_REASON_PREFIX,
|
|
)
|
|
headroom = max(0, _order_queue_target_pending() - pending)
|
|
backfill_reserved = _backfill_reserved_slots()
|
|
accounts, demand_ids, commodity_ids = _refresh_candidates(
|
|
db,
|
|
job,
|
|
now,
|
|
batch_limit=headroom,
|
|
backfill_floor=backfill_reserved,
|
|
)
|
|
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 if is_demand_refresh else 30,
|
|
reason=(
|
|
("待履约商品补货: " + ",".join(commodity_ids[:5]))
|
|
if is_demand_refresh and commodity_ids
|
|
else "账号商品能力补全"
|
|
)[:255],
|
|
due_at=now,
|
|
)
|
|
db.commit()
|
|
queued = len(accounts)
|
|
return {
|
|
"scanned": len(accounts),
|
|
"success": queued,
|
|
"invalid": 0,
|
|
"skipped": 0,
|
|
"message": (
|
|
f"本轮筛选 {len(accounts)} 个需刷新能力账号,新入队 {queued} 个"
|
|
if accounts
|
|
else "没有需要补全商品能力缓存的 CK 有效账号"
|
|
),
|
|
"detail": {
|
|
"queued": queued,
|
|
"pending": pending,
|
|
"order_cap": _order_queue_target_pending(),
|
|
"headroom": headroom,
|
|
"backfill_reserved": backfill_reserved,
|
|
"commodities": commodity_ids[:20],
|
|
"demand_refresh": len(demand_ids),
|
|
"backfill_refresh": max(0, queued - len(demand_ids)),
|
|
},
|
|
}
|
|
|
|
|
|
__all__ = [
|
|
"JOB_KEY",
|
|
"build_select_query",
|
|
"run_account_capability_refresh",
|
|
]
|