Files
live-hub-py/web/backend/services/platform_fulfillment/account_selector.py
T

1151 lines
36 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""直播账号履约的账号筛选与租约。
只复用账号池中经过验证的筛选与数据库唯一约束,不引入自动充值、自动兑换
或多活动 scope。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import and_, case, func, literal, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, aliased
from ...models import (
Account,
AccountCommodityState,
AccountEvent,
AccountLease,
AccountSyncState,
)
from ..account_capability_service import OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE
from ..account_events_service import (
CATEGORY_OPS,
EVENT_LEASE_ACQUIRED,
EVENT_LEASE_RELEASED,
emit,
)
from ..account_query_filters import (
active_collab_order_exists,
active_lease_exists,
assigned_to_pool_filter,
automatable_account_filter,
cookie_present_filter,
fresh_eligible_state_filter,
role_change_ready_filter,
valid_ck_filter,
)
from ..account_sync_runner import WORK_STOREHOME_SYNC
from ..account_work_queue import active_account_work_exists, active_account_work_ids
from .policy import (
PRIORITY_KEY_BUNDLE_MATCH,
PRIORITY_KEY_CK_FRESHNESS,
PRIORITY_KEY_POINTS_ASC,
PRIORITY_KEY_PRESERVE_BUNDLE_POOL,
PRIORITY_KEY_RESOURCE_READY,
normalize_priority_order,
)
VALIDATION_LEASE_MINUTES = 5
BINDING_LEASE_MINUTES = 120
EXCHANGE_COOLDOWN_DAYS = 365
@dataclass(frozen=True)
class AccountCandidate:
account_id: int
username: str
nickname: str
points: int
gold_balance: int | None
points_expire_at: datetime | None
role_change_available_at: datetime | None
@property
def display_name(self) -> str:
return self.nickname or self.username or f"#{self.account_id}"
@dataclass(frozen=True)
class CapabilityCandidate:
"""一个新鲜能力快照及其对应账号,供本地零外部请求选号。"""
account: CapabilityAccount
state: CapabilityState
@dataclass(frozen=True)
class CapabilityAccount:
"""能力选号实际需要的账号字段,不加载 CK / JSON 等大列。"""
id: int
username: str
nickname: str
uid: str
points: int | None
gold_balance: int | None
points_expire_at: datetime | None
role_change_available_at: datetime | None
elite_opened: bool | None
role_bind_status: str
ck_check_status: str
game_name: str
ck_checked_at: datetime | None = None
status: str = ""
@dataclass(frozen=True)
class CapabilityState:
"""选号排序之后才需要的能力快照详情。"""
account_eligibility: str
offer_state: str
observed_at: datetime | None
available_from: datetime | None
valid_until: datetime | None
blocking_reason: str
bundle_missing_count: int = 0
is_protected_bundle: bool = False
def _now(now: datetime | None = None) -> datetime:
return now or datetime.now(UTC)
def eligible_accounts(
db: Session,
*,
commodity_id: str,
required_points: int,
now: datetime | None = None,
limit: int = 20,
) -> list[AccountCandidate]:
"""筛选能人工兑换指定精英宝典商品的账号。"""
moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
exchanged = (
select(AccountEvent.id)
.where(
AccountEvent.account_id == Account.id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key == commodity_id,
AccountEvent.occurred_at >= since,
)
.exists()
)
rows = (
db.query(Account)
.filter(
Account.status == "active",
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
Account.elite_opened.is_(True),
Account.points.isnot(None),
Account.points >= max(0, int(required_points)),
assigned_to_pool_filter(),
~active_lease_exists(),
~active_collab_order_exists(),
~exchanged,
role_change_ready_filter(moment),
)
.order_by(
Account.points_expire_at.is_(None),
Account.points_expire_at.asc(),
Account.points.asc(),
Account.id.asc(),
)
.limit(max(1, min(int(limit), 100)))
.all()
)
return [
AccountCandidate(
account_id=row.id,
username=row.username,
nickname=row.nickname or "",
points=int(row.points or 0),
gold_balance=row.gold_balance,
points_expire_at=row.points_expire_at,
role_change_available_at=row.role_change_available_at,
)
for row in rows
]
def live_candidate_accounts(
db: Session,
*,
limit: int = 20,
required_points: int = 0,
commodity_id: str = "",
prefer_unbound: bool = False,
empty_only: bool = False,
) -> list[Account]:
"""按缓存质量优先排序,但保留实时检测作为最终准入判断。"""
query = db.query(Account).filter(
cookie_present_filter(),
automatable_account_filter(),
role_change_ready_filter(_now()),
assigned_to_pool_filter(),
~active_lease_exists(),
~active_collab_order_exists(),
)
commodity = commodity_id.strip()
if commodity:
since = _now() - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
exchanged = (
select(AccountEvent.id)
.where(
AccountEvent.account_id == Account.id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key == commodity,
AccountEvent.occurred_at >= since,
)
.exists()
)
query = query.filter(~exchanged)
if empty_only:
query = query.filter(Account.role_bind_status == "unbound")
effective_limit = max(1, min(int(limit), 100))
required = max(0, int(required_points))
# Keep the old priority order, but turn it into disjoint indexed queries.
# A single ORDER BY CASE forced MySQL to sort the whole account pool; each
# tier below can stop as soon as it has enough rows.
tiers = (
(True, "active", True, True),
(True, "active", True, False),
(True, "active", False, True),
(True, "active", False, False),
(True, "not_active", True, True),
(True, "not_active", True, False),
(True, "not_active", False, True),
(True, "not_active", False, False),
(False, "active", True, True),
(False, "active", True, False),
(False, "active", False, True),
(False, "active", False, False),
(False, "not_active", True, True),
(False, "not_active", True, False),
(False, "not_active", False, True),
(False, "not_active", False, False),
)
rows: list[Account] = []
for ck_valid, status_active, elite_opened, points_enough in tiers:
if ck_valid:
tier_query = query.filter(Account.ck_check_status == "valid")
else:
tier_query = query.filter(Account.ck_check_status != "valid")
if status_active == "active":
tier_query = tier_query.filter(Account.status == "active")
else:
tier_query = tier_query.filter(Account.status != "active")
tier_query = tier_query.filter(
Account.elite_opened.is_(True)
if elite_opened
else Account.elite_opened.is_not(True)
)
tier_query = tier_query.filter(
Account.points >= required
if points_enough
else or_(Account.points.is_(None), Account.points < required)
)
order_by = [
Account.ck_checked_at.is_(None).desc(),
Account.ck_checked_at.asc(),
Account.points.asc(),
Account.id.asc(),
]
if prefer_unbound:
order_by.insert(
0,
case((Account.role_bind_status == "unbound", 0), else_=1),
)
rows.extend(
tier_query.order_by(*order_by).limit(effective_limit - len(rows)).all()
)
if len(rows) >= effective_limit:
break
return rows
def _co_commodity_eligible_exists(
commodity_id: str,
*,
scope: str,
moment: datetime,
since: datetime,
):
"""协同商品资格子查询:只要账号本身具备可兑资格(含未开放预售)且近 365 天未兑过。"""
co_state = aliased(AccountCommodityState)
return (
select(co_state.id)
.where(
co_state.account_id == Account.id,
co_state.platform == "douyu",
co_state.scope == scope,
co_state.commodity_id == commodity_id,
fresh_eligible_state_filter(
moment,
allow_before_open=True,
state_model=co_state,
),
or_(
co_state.last_exchange_at.is_(None),
co_state.last_exchange_at < since,
),
)
.correlate(Account)
.exists()
)
def _clean_commodity_group(
values: tuple[str, ...] | list[str] | None,
*,
exclude: str = "",
) -> tuple[str, ...]:
seen: list[str] = []
for raw in values or ():
text = str(raw or "").strip()
if text and text != exclude and text not in seen:
seen.append(text)
return tuple(seen)
def _capability_candidate_query(
db: Session,
*,
commodity_id: str,
required_points: int = 0,
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
allow_before_open: bool = False,
required_co_commodities: tuple[str, ...] | list[str] = (),
preferred_co_commodities: tuple[str, ...] | list[str] = (),
protected_bundle_commodities: tuple[str, ...] | list[str] = (),
priority_order: tuple[str, ...] | list[str] = (),
):
commodity = commodity_id.strip()
if not commodity:
return None
moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
eligibility_filter = fresh_eligible_state_filter(
moment,
allow_before_open=allow_before_open,
)
required_co = _clean_commodity_group(required_co_commodities, exclude=commodity)
preferred_co = _clean_commodity_group(
preferred_co_commodities,
exclude=commodity,
)
preferred_co = tuple(cid for cid in preferred_co if cid not in required_co)
protected_co = _clean_commodity_group(protected_bundle_commodities)
filters = [
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity,
eligibility_filter,
or_(
AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at < since,
),
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
role_change_ready_filter(moment),
assigned_to_pool_filter(),
~active_lease_exists(),
~active_collab_order_exists(),
]
for co_cid in required_co:
filters.append(
_co_commodity_eligible_exists(
co_cid,
scope=scope,
moment=moment,
since=since,
)
)
if preferred_co:
missing_terms = [
case(
(
_co_commodity_eligible_exists(
co_cid,
scope=scope,
moment=moment,
since=since,
),
0,
),
else_=1,
)
for co_cid in preferred_co
]
missing_count_expr = missing_terms[0]
for term in missing_terms[1:]:
missing_count_expr = missing_count_expr + term
else:
missing_count_expr = literal(0)
if protected_co:
all_protected_expr = and_(
*[
_co_commodity_eligible_exists(
co_cid,
scope=scope,
moment=moment,
since=since,
)
for co_cid in protected_co
]
)
protected_flag_expr = case((all_protected_expr, 1), else_=0)
else:
protected_flag_expr = literal(0)
order_clauses: list[Any] = [
case(
(AccountCommodityState.offer_state == OFFER_STATE_ACTIVE, 0),
else_=1,
)
]
for key in normalize_priority_order(priority_order):
if key == PRIORITY_KEY_BUNDLE_MATCH and preferred_co:
order_clauses.append(missing_count_expr.asc())
elif key == PRIORITY_KEY_PRESERVE_BUNDLE_POOL and protected_co:
order_clauses.append(protected_flag_expr.asc())
elif key == PRIORITY_KEY_RESOURCE_READY:
order_clauses.extend(
[
case((Account.elite_opened.is_(True), 0), else_=1),
case(
(Account.points >= max(0, int(required_points)), 0),
else_=1,
),
]
)
elif key == PRIORITY_KEY_POINTS_ASC:
order_clauses.extend(
[
Account.points.is_(None).asc(),
Account.points.asc(),
]
)
elif key == PRIORITY_KEY_CK_FRESHNESS:
order_clauses.extend(
[
case((Account.ck_check_status == "valid", 0), else_=1),
case((Account.status == "active", 0), else_=1),
Account.ck_checked_at.is_(None).asc(),
Account.ck_checked_at.desc(),
]
)
order_clauses.extend(
[
AccountCommodityState.observed_at.desc(),
Account.id.asc(),
]
)
return (
db.query(
Account.id.label("account_id"),
Account.username.label("account_username"),
Account.nickname.label("account_nickname"),
Account.uid.label("account_uid"),
Account.points.label("account_points"),
Account.gold_balance.label("account_gold_balance"),
Account.points_expire_at.label("account_points_expire_at"),
Account.role_change_available_at.label("account_role_change_available_at"),
Account.elite_opened.label("account_elite_opened"),
Account.role_bind_status.label("account_role_bind_status"),
Account.ck_check_status.label("account_ck_check_status"),
Account.ck_checked_at.label("account_ck_checked_at"),
Account.status.label("account_status"),
Account.game_name.label("account_game_name"),
AccountCommodityState.offer_state.label("state_offer_state"),
AccountCommodityState.observed_at.label("state_observed_at"),
missing_count_expr.label("bundle_missing_count"),
protected_flag_expr.label("is_protected_bundle"),
)
.join(
AccountCommodityState,
AccountCommodityState.account_id == Account.id,
)
.filter(*filters)
.order_by(*order_clauses)
.limit(max(1, min(int(limit), 100)))
)
def capability_candidate_rows(
db: Session,
*,
commodity_id: str,
required_points: int = 0,
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
allow_before_open: bool = False,
required_co_commodities: tuple[str, ...] | list[str] = (),
preferred_co_commodities: tuple[str, ...] | list[str] = (),
protected_bundle_commodities: tuple[str, ...] | list[str] = (),
priority_order: tuple[str, ...] | list[str] = (),
) -> list[CapabilityCandidate]:
"""读取账号与能力快照;只访问本地数据库,不触发官网请求。"""
query = _capability_candidate_query(
db,
commodity_id=commodity_id,
required_points=required_points,
scope=scope,
limit=limit,
now=now,
allow_before_open=allow_before_open,
required_co_commodities=required_co_commodities,
preferred_co_commodities=preferred_co_commodities,
protected_bundle_commodities=protected_bundle_commodities,
priority_order=priority_order,
)
if query is None:
return []
rows = query.all()
if not rows:
return []
account_ids = [int(row.account_id) for row in rows]
state_rows = (
db.query(
AccountCommodityState.account_id,
AccountCommodityState.account_eligibility,
AccountCommodityState.offer_state,
AccountCommodityState.observed_at,
AccountCommodityState.available_from,
AccountCommodityState.valid_until,
AccountCommodityState.blocking_reason,
)
.filter(
AccountCommodityState.account_id.in_(account_ids),
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id.strip(),
)
.all()
)
states = {
int(row.account_id): CapabilityState(
account_eligibility=str(row.account_eligibility or ""),
offer_state=str(row.offer_state or ""),
observed_at=row.observed_at,
available_from=row.available_from,
valid_until=row.valid_until,
blocking_reason=str(row.blocking_reason or ""),
)
for row in state_rows
}
candidates: list[CapabilityCandidate] = []
for row in rows:
account_id = int(row.account_id)
base_state = states.get(account_id)
if base_state is None:
continue
state = CapabilityState(
account_eligibility=base_state.account_eligibility,
offer_state=base_state.offer_state,
observed_at=base_state.observed_at,
available_from=base_state.available_from,
valid_until=base_state.valid_until,
blocking_reason=base_state.blocking_reason,
bundle_missing_count=int(getattr(row, "bundle_missing_count", 0) or 0),
is_protected_bundle=bool(getattr(row, "is_protected_bundle", 0)),
)
candidates.append(
CapabilityCandidate(
account=CapabilityAccount(
id=account_id,
username=str(row.account_username or ""),
nickname=str(row.account_nickname or ""),
uid=str(row.account_uid or ""),
points=row.account_points,
gold_balance=row.account_gold_balance,
points_expire_at=row.account_points_expire_at,
role_change_available_at=(row.account_role_change_available_at),
elite_opened=row.account_elite_opened,
role_bind_status=str(row.account_role_bind_status or ""),
ck_check_status=str(row.account_ck_check_status or ""),
game_name=str(row.account_game_name or ""),
ck_checked_at=getattr(row, "account_ck_checked_at", None),
status=str(getattr(row, "account_status", "") or ""),
),
state=state,
)
)
return candidates
def capability_candidate_accounts(
db: Session,
*,
commodity_id: str,
required_points: int = 0,
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
allow_before_open: bool = False,
required_co_commodities: tuple[str, ...] | list[str] = (),
preferred_co_commodities: tuple[str, ...] | list[str] = (),
protected_bundle_commodities: tuple[str, ...] | list[str] = (),
priority_order: tuple[str, ...] | list[str] = (),
) -> list[CapabilityAccount]:
"""从新鲜的商品能力索引读取候选账号,不产生外部请求。"""
return [
candidate.account
for candidate in capability_candidate_rows(
db,
commodity_id=commodity_id,
required_points=required_points,
scope=scope,
limit=limit,
now=now,
allow_before_open=allow_before_open,
required_co_commodities=required_co_commodities,
preferred_co_commodities=preferred_co_commodities,
protected_bundle_commodities=protected_bundle_commodities,
priority_order=priority_order,
)
]
def _refresh_tiebreaker_order_by() -> tuple[Any, ...]:
return (
Account.overview_queried_at.is_(None).desc(),
Account.overview_queried_at.asc(),
Account.id.asc(),
)
def _refresh_priority_tier0_filter(now: datetime):
return and_(
~active_lease_exists(),
~active_collab_order_exists(),
role_change_ready_filter(now),
Account.role_bind_status == "unbound",
)
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),
*_refresh_tiebreaker_order_by(),
)
def _pool_refresh_base_query(
db: Session,
*,
excluded_ids: tuple[int, ...] = (),
):
query = db.query(Account).filter(
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
)
active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC)
if active_work_ids is None:
query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC))
elif active_work_ids:
query = query.filter(~Account.id.in_(active_work_ids))
if excluded_ids:
query = query.filter(~Account.id.in_(excluded_ids))
return query
def _select_refresh_candidates_tier0_first(
db: Session,
*,
base_pool,
condition,
moment: datetime,
limit: int,
) -> list[Account]:
"""优先只取最高优先级窗口账号再校验商品明细,避免全池 1.1 万账号逐行扫 45 条商品。"""
effective_limit = max(1, min(int(limit), 100))
window_limit = max(effective_limit * 4, 200)
tier0_ids = [
int(account_id)
for (account_id,) in (
base_pool.with_entities(Account.id)
.filter(_refresh_priority_tier0_filter(moment))
.order_by(*_refresh_tiebreaker_order_by())
.limit(window_limit)
.all()
)
]
if not tier0_ids:
return (
base_pool.filter(condition)
.order_by(*_refresh_candidate_order_by(moment))
.limit(effective_limit)
.all()
)
collected = (
db.query(Account)
.filter(Account.id.in_(tier0_ids), condition)
.order_by(*_refresh_tiebreaker_order_by())
.limit(effective_limit)
.all()
)
if len(collected) >= effective_limit:
return collected[:effective_limit]
remaining = effective_limit - len(collected)
rest = (
base_pool.filter(~Account.id.in_(tier0_ids), condition)
.order_by(*_refresh_candidate_order_by(moment))
.limit(remaining)
.all()
)
return [*collected, *rest]
def capability_refresh_candidate_accounts(
db: Session,
*,
commodity_ids: list[str] | tuple[str, ...],
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
) -> list[Account]:
"""为待履约商品补充候选账号。
2026-11-22:原刷新作业只扫描已有商品状态行的账号,新账号永远不会被
发现;后续又错误地只扫描“此刻可分配”的账号。能力目录必须覆盖全部有效
CK,租约、协作占用和换绑冷却只影响“选号”,不能影响“补目录”。
"""
commodities = tuple(dict.fromkeys(str(item).strip() for item in commodity_ids))
commodities = tuple(item for item in commodities if item)
if not commodities:
return []
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()
)
state_due = (
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id.in_(commodities),
or_(
AccountCommodityState.valid_until.is_(None),
AccountCommodityState.valid_until <= moment,
AccountCommodityState.next_check_at.is_(None),
AccountCommodityState.next_check_at <= moment,
),
)
.exists()
)
if len(commodities) == 1:
missing_state = ~(
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodities[0],
)
.exists()
)
else:
# (account_id, platform, scope, commodity_id) 有唯一约束 uq_account_commodity_state,
# 行数少于待履约商品数即表示至少缺失一个商品的快照行。
missing_state = (
select(func.count(AccountCommodityState.id))
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id.in_(commodities),
)
.scalar_subquery()
< len(commodities)
)
base_pool = _pool_refresh_base_query(db)
needs_refresh = or_(
state_due,
and_(~fresh_storehome, missing_state),
)
return _select_refresh_candidates_tier0_first(
db,
base_pool=base_pool,
condition=needs_refresh,
moment=moment,
limit=limit,
)
def storehome_refresh_candidate_accounts(
db: Session,
*,
limit: int = 20,
now: datetime | None = None,
exclude_account_ids: tuple[int, ...] | list[int] = (),
scope: str = "elite",
preferred_commodity_groups: tuple[tuple[str, ...], ...] = (),
) -> 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)
)
preferred_groups = tuple(
dict.fromkeys(
tuple(
dict.fromkeys(
str(commodity_id).strip()
for commodity_id in group
if str(commodity_id).strip()
)
)
for group in preferred_commodity_groups
)
)
preferred_groups = tuple(group for group in preferred_groups if len(group) >= 2)
preferred_exprs = [
and_(
*[
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.account_eligibility == "eligible",
AccountCommodityState.offer_state.in_(
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
),
or_(
AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at
< moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS),
),
)
.exists()
for commodity_id in group
]
)
for group in preferred_groups
]
base_pool = _pool_refresh_base_query(db, excluded_ids=excluded_ids)
if not preferred_exprs:
return _select_refresh_candidates_tier0_first(
db,
base_pool=base_pool,
condition=~fresh_storehome,
moment=moment,
limit=limit,
)
query = base_pool.filter(~fresh_storehome)
order_by: list[Any] = [case((or_(*preferred_exprs), 0), else_=1)]
order_by.extend(_refresh_candidate_order_by(moment))
return query.order_by(*order_by).limit(max(1, min(int(limit), 100))).all()
def has_recent_exchange(
db: Session,
*,
account_id: int,
commodity_id: str,
now: datetime | None = None,
) -> bool:
moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
return (
db.query(AccountEvent.id)
.filter(
AccountEvent.account_id == account_id,
AccountEvent.event_type == "exchange",
AccountEvent.subject_key == commodity_id,
AccountEvent.occurred_at >= since,
)
.first()
is not None
)
def lease_account(
db: Session,
*,
candidate: AccountCandidate,
holder_user_id: int,
task_id: int,
commodity_id: str,
ttl_minutes: int | None = None,
now: datetime | None = None,
commit: bool = True,
) -> AccountLease | None:
"""尝试领取一个账号;撞唯一索引时返回 None。"""
return acquire_account_lease(
db,
account_id=int(candidate.account_id),
holder_user_id=holder_user_id,
scope="elite",
purpose="platform_fulfillment",
commodity_id=commodity_id,
batch_id=f"pf:{task_id}",
ttl_minutes=ttl_minutes,
now=now,
commit=commit,
)
def acquire_account_lease(
db: Session,
*,
account_id: int,
holder_user_id: int,
scope: str,
purpose: str,
commodity_id: str = "",
batch_id: str = "",
ttl_minutes: int | None = None,
now: datetime | None = None,
commit: bool = True,
) -> AccountLease | None:
"""获取账号租约;调用方可在自己的事务内复用。
唯一索引负责并发互斥。撞到已有活动租约时返回 ``None``,由调用方结合
``active_lease_for_account`` 决定是沿用合法占用的租约还是提示冲突。
"""
moment = _now(now)
lease = AccountLease(
account_id=int(account_id),
holder_user_id=holder_user_id,
scope=str(scope or "elite")[:16],
purpose=str(purpose or "exchange")[:24],
commodity_id=str(commodity_id or "")[:64],
batch_id=str(batch_id or "")[:64],
status="active",
leased_at=moment,
expires_at=(
None
if ttl_minutes is None
else moment + timedelta(minutes=max(1, int(ttl_minutes)))
),
release_reason="",
created_at=moment,
)
try:
with db.begin_nested():
db.add(lease)
db.flush()
except IntegrityError:
if lease in db:
db.expunge(lease)
return None
event_detail: dict[str, object] = {
"lease_id": lease.id,
"holder_user_id": holder_user_id,
"commodity_id": commodity_id,
"purpose": purpose,
"batch_id": batch_id,
}
if purpose == "platform_fulfillment" and batch_id.startswith("pf:"):
event_detail["task_id"] = int(batch_id.removeprefix("pf:"))
emit(
db,
account_id=int(account_id),
event_type=EVENT_LEASE_ACQUIRED,
title=(
f"履约占用:任务 #{batch_id.removeprefix('pf:')}"
if purpose == "platform_fulfillment"
else f"业务占用:{purpose}"
),
category=CATEGORY_OPS,
occurred_at=moment,
detail=event_detail,
source="lease",
subject_type="task" if purpose == "platform_fulfillment" else "lease",
subject_key=batch_id,
actor_type="user",
actor_id=holder_user_id,
source_ref=f"account_lease_acquired:{lease.id}",
)
if commit:
db.commit()
return lease
def active_lease_for_account(
db: Session, account_id: int | None
) -> AccountLease | None:
if not account_id:
return None
return (
db.query(AccountLease)
.filter(
AccountLease.account_id == int(account_id),
AccountLease.status == "active",
)
.first()
)
def renew_lease(
db: Session,
lease: AccountLease,
*,
ttl_minutes: int | None = None,
now: datetime | None = None,
) -> AccountLease:
if lease.status != "active":
raise ValueError("租约已结束,不能续期")
lease.expires_at = (
None
if ttl_minutes is None
else _now(now) + timedelta(minutes=max(1, int(ttl_minutes)))
)
db.commit()
return lease
def release_lease(
db: Session,
lease: AccountLease | None,
*,
reason: str,
now: datetime | None = None,
commit: bool = True,
) -> bool:
if lease is None or lease.status != "active":
return False
lease.status = "released"
lease.released_at = _now(now)
lease.release_reason = str(reason or "")[:64]
emit(
db,
account_id=int(lease.account_id),
event_type=EVENT_LEASE_RELEASED,
title=f"释放履约占用:{reason}",
category=CATEGORY_OPS,
detail={
"lease_id": lease.id,
"task_id": lease.batch_id,
"reason": str(reason or "")[:64],
},
source="lease",
subject_type="lease",
subject_key=str(lease.id),
actor_type="system",
source_ref=f"account_lease_released:{lease.id}",
)
if commit:
db.commit()
return True
def expire_platform_fulfillment_leases(
db: Session,
*,
now: datetime | None = None,
limit: int = 500,
) -> int:
moment = _now(now)
leases = (
db.query(AccountLease)
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
AccountLease.expires_at.isnot(None),
AccountLease.expires_at <= moment,
)
.order_by(AccountLease.id.asc())
.limit(max(1, int(limit)))
.all()
)
for lease in leases:
lease.status = "expired"
lease.released_at = moment
lease.release_reason = "ttl_expired"
emit(
db,
account_id=int(lease.account_id),
event_type=EVENT_LEASE_RELEASED,
title="履约租约已过期",
category=CATEGORY_OPS,
occurred_at=moment,
detail={
"lease_id": lease.id,
"task_id": lease.batch_id,
"reason": "ttl_expired",
},
source="lease",
subject_type="lease",
subject_key=str(lease.id),
actor_type="system",
source_ref=f"account_lease_released:{lease.id}",
)
if leases:
db.commit()
return len(leases)
__all__ = [
"BINDING_LEASE_MINUTES",
"EXCHANGE_COOLDOWN_DAYS",
"VALIDATION_LEASE_MINUTES",
"AccountCandidate",
"CapabilityAccount",
"acquire_account_lease",
"active_lease_for_account",
"capability_candidate_accounts",
"capability_refresh_candidate_accounts",
"eligible_accounts",
"expire_platform_fulfillment_leases",
"has_recent_exchange",
"lease_account",
"live_candidate_accounts",
"release_lease",
"renew_lease",
"storehome_refresh_candidate_accounts",
]