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

1352 lines
48 KiB
Python

"""能力池诊断、自动选号和租约分配。"""
from __future__ import annotations
import os
from datetime import datetime, timedelta
from typing import Any
from fastapi import HTTPException
from sqlalchemy import case, func, or_, select
from sqlalchemy.orm import Session
from ...models import (
Account,
AccountCommodityState,
AccountEvent,
AccountLease,
DouyuTask,
PlatformFulfillmentTask,
User,
)
from ..account_capability_service import (
AVAILABILITY_AVAILABLE,
AVAILABILITY_LIMITED,
AVAILABILITY_NOT_OPEN,
OFFER_STATE_ACTIVE,
OFFER_STATE_BEFORE,
allocation_availability,
)
from ..account_lifecycle import MANUAL_STATES
from ..account_query_filters import (
active_collab_order_exists,
active_lease_exists,
assigned_to_pool_filter,
automatable_account_filter,
cookie_present_filter,
role_change_ready_filter,
valid_ck_filter,
)
from ..account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, WORK_STOREHOME_SYNC
from ..account_work_queue import (
active_account_work_count,
enqueue_account_work,
)
from ..binding_ownership import (
active_collab_order_for_account,
role_names_match,
)
from ..douyu_account_state import DouyuLiveAccountState
from . import classification
from .account_selector import (
EXCHANGE_COOLDOWN_DAYS,
AccountCandidate,
CapabilityCandidate,
capability_candidate_rows,
capability_refresh_candidate_accounts,
lease_account,
release_lease,
)
from .common import (
DEFAULT_CAPABILITY_CANDIDATE_LIMIT,
FLOW_VERSION_CLEAN,
LOCAL_CACHE_MISS_RETRY_SECONDS,
LOCAL_LEASE_CONFLICT_RETRY_SECONDS,
LOCAL_STOCK_RETRY_SECONDS,
SCOPE_ELITE,
TARGET_PLATFORM,
_exchange_gate,
_jsonable,
_now,
)
from .outbox import _emit_order_site_binding_state
from .policy import (
PRIORITY_KEY_BUNDLE_MATCH,
PRIORITY_KEY_CK_FRESHNESS,
PRIORITY_KEY_POINTS_ASC,
PRIORITY_KEY_PRESERVE_BUNDLE_POOL,
PRIORITY_KEY_RESOURCE_READY,
bundle_requirements_for_commodity,
normalize_allocation_policy,
normalize_priority_order,
protected_bundle_commodities,
)
from .repository import _load_task, _load_task_for_update
from .role_lock import find_account_lock, find_role_lock
from .runtime import (
_append_event,
_apply_task_lease_policy,
_lease_duration_minutes,
get_settings,
)
from .views import get_task_detail
def _cached_capability_state(
candidate: CapabilityCandidate,
*,
commodity_id: str,
) -> DouyuLiveAccountState:
"""把新鲜本地能力快照转换成统一的履约状态,不访问斗鱼官网。"""
account = candidate.account
state = candidate.state
availability = allocation_availability(
state.account_eligibility,
state.offer_state,
)
if availability == AVAILABILITY_AVAILABLE:
reason = ""
elif availability == AVAILABILITY_LIMITED:
reason = "该账号已达此商品兑换上限"
elif availability == AVAILABILITY_NOT_OPEN:
reason = (
f"限时兑换未开始,开始于 {state.available_from.isoformat()}"
if state.available_from
else "活动尚未开放兑换"
)
else:
reason = str(state.blocking_reason or "")
return DouyuLiveAccountState(
account_id=int(account.id),
account_name=account.nickname or account.username or f"#{account.id}",
checked_at=state.observed_at or _now(),
ck_verdict="valid",
ck_message="本地能力快照关联账号 CK 有效",
elite_opened=account.elite_opened,
points=account.points,
limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at,
commodity_availability={commodity_id: availability},
commodity_blocking_reasons=({commodity_id: reason} if reason else {}),
)
def _capability_availability_counts(
db: Session,
*,
commodity_id: str,
scope: str,
now: datetime,
) -> dict[str, Any]:
base = db.query(AccountCommodityState).filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
eligibility_rows = (
base.with_entities(
AccountCommodityState.account_eligibility,
func.count(AccountCommodityState.id),
)
.group_by(AccountCommodityState.account_eligibility)
.all()
)
offer_rows = (
db.query(
AccountCommodityState.offer_state, func.count(AccountCommodityState.id)
)
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
.group_by(AccountCommodityState.offer_state)
.all()
)
stock_rows = (
db.query(
AccountCommodityState.stock_state, func.count(AccountCommodityState.id)
)
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
.group_by(AccountCommodityState.stock_state)
.all()
)
eligible_account_ids = (
select(AccountCommodityState.account_id)
.where(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.account_eligibility == "eligible",
AccountCommodityState.offer_state.in_(
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > now,
)
.distinct()
)
account_base = db.query(Account).filter(Account.id.in_(eligible_account_ids))
eligible_accounts = int(account_base.count())
role_ready_accounts = int(
account_base.filter(role_change_ready_filter(now)).count()
)
leased_accounts = int(account_base.filter(active_lease_exists()).count())
collab_accounts = int(account_base.filter(active_collab_order_exists()).count())
allocatable_accounts = int(
account_base.filter(
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
role_change_ready_filter(now),
~active_lease_exists(),
~active_collab_order_exists(),
).count()
)
next_role_ready_at = (
account_base.filter(
Account.role_change_available_at.isnot(None),
Account.role_change_available_at > now,
)
.with_entities(func.min(Account.role_change_available_at))
.scalar()
)
return {
**{f"eligibility:{key}": int(count or 0) for key, count in eligibility_rows},
**{f"offer:{key}": int(count or 0) for key, count in offer_rows},
**{f"stock:{key}": int(count or 0) for key, count in stock_rows},
"account:eligible": eligible_accounts,
"account:roleReady": role_ready_accounts,
"account:roleCooldown": max(0, eligible_accounts - role_ready_accounts),
"account:leased": leased_accounts,
"account:activeCollab": collab_accounts,
"account:allocatable": allocatable_accounts,
"account:nextRoleReadyAt": _jsonable(next_role_ready_at),
}
def _local_allocation_retry_at(
db: Session,
*,
task: PlatformFulfillmentTask,
now: datetime,
availability_counts: dict[str, int],
lease_conflict: bool,
) -> tuple[datetime, str]:
"""按本地状态决定下一轮时间,避免永久无库存任务每 45 秒占槽。"""
if lease_conflict:
return (
now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS),
"lease_conflict",
)
next_open_at = (
db.query(func.min(AccountCommodityState.available_from))
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == (task.scope or SCOPE_ELITE),
AccountCommodityState.commodity_id == task.commodity_id,
AccountCommodityState.offer_state == OFFER_STATE_BEFORE,
AccountCommodityState.available_from.isnot(None),
AccountCommodityState.available_from > now,
)
.scalar()
)
if next_open_at is not None:
return next_open_at + timedelta(seconds=5), "commodity_not_open"
if availability_counts.get(f"offer:{OFFER_STATE_BEFORE}"):
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "commodity_not_open"
has_capability_rows = any(
int(value or 0)
for key, value in availability_counts.items()
if key.startswith(("eligibility:", "offer:", "stock:"))
)
if has_capability_rows:
if int(availability_counts.get("account:allocatable") or 0) > 0:
return (
now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS),
"lease_conflict",
)
if int(availability_counts.get("account:roleCooldown") or 0) > 0:
return (
now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS),
"account_role_cooldown",
)
if int(availability_counts.get("account:eligible") or 0) > 0:
return (
now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS),
"account_pool_busy",
)
return now + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS), "no_eligible_account"
return now + timedelta(
seconds=LOCAL_CACHE_MISS_RETRY_SECONDS
), "capability_cache_miss"
def _seed_capability_refresh(
db: Session,
*,
task: PlatformFulfillmentTask,
now: datetime,
) -> int:
"""能力池不足时只入队独立同步槽,不在分配线程里请求官网。"""
try:
seed_limit = int(
os.getenv("PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT", "20")
)
except ValueError:
seed_limit = 20
seed_limit = max(1, min(seed_limit, 100))
try:
target_pending = max(
1,
int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")),
)
except ValueError:
target_pending = 60
pending = active_account_work_count(
db,
work_types=ACCOUNT_SYNC_WORK_TYPES,
)
headroom = max(0, target_pending - pending)
if headroom <= 0:
return 0
accounts = capability_refresh_candidate_accounts(
db,
commodity_ids=[task.commodity_id],
scope=task.scope or SCOPE_ELITE,
limit=min(seed_limit, headroom),
now=now,
)
for account in accounts:
enqueue_account_work(
db,
account_id=int(account.id),
work_type=WORK_STOREHOME_SYNC,
priority=20,
due_at=now,
reason=f"履约任务 #{task.id} 缺少商品能力快照",
payload={
"commodity_id": task.commodity_id,
"platform_task_id": int(task.id),
},
)
return len(accounts)
def _candidate_sort_key(
candidate: CapabilityCandidate,
cached_state: DouyuLiveAccountState,
*,
required_points: int,
priority_order: list[str] | tuple[str, ...],
) -> tuple[Any, ...]:
"""保持与 SQL 查询一致的多维度优先级排序,避免 Python 二次排序打乱保护顺序。"""
account = candidate.account
state = candidate.state
parts: list[Any] = [0 if state.offer_state == OFFER_STATE_ACTIVE else 1]
for key in normalize_priority_order(priority_order):
if key == PRIORITY_KEY_BUNDLE_MATCH:
parts.append(int(state.bundle_missing_count or 0))
elif key == PRIORITY_KEY_PRESERVE_BUNDLE_POOL:
parts.append(1 if state.is_protected_bundle else 0)
elif key == PRIORITY_KEY_RESOURCE_READY:
parts.append(cached_state.readiness_rank(required_points=required_points))
elif key == PRIORITY_KEY_POINTS_ASC:
parts.append(1 if cached_state.points is None else 0)
parts.append(int(cached_state.points or 0))
elif key == PRIORITY_KEY_CK_FRESHNESS:
checked_at = account.ck_checked_at
parts.append(0 if account.ck_check_status == "valid" else 1)
parts.append(0 if account.status == "active" else 1)
parts.append(1 if checked_at is None else 0)
parts.append(-(checked_at.timestamp()) if checked_at is not None else 0.0)
parts.append(int(account.id))
return tuple(parts)
def _apply_allocated_account_state(
db: Session,
*,
task: PlatformFulfillmentTask,
account_id: int,
account_name: str,
lease: AccountLease,
cached_state: DouyuLiveAccountState,
required_points: int,
is_presale: bool,
current: User,
moment: datetime,
allocation_strategy: str,
observed_at: datetime | None = None,
valid_until: datetime | None = None,
extra_event_detail: dict[str, Any] | None = None,
already_bound_role: str = "",
commit: bool = True,
) -> dict[str, Any]:
stale_leases = (
db.query(AccountLease)
.filter(
AccountLease.status == "active",
AccountLease.batch_id == f"pf:{int(task.id)}",
AccountLease.id != int(lease.id),
)
.with_for_update()
.all()
)
for stale in stale_leases:
release_lease(
db,
stale,
reason="allocation_replaced",
commit=False,
)
task.account_id = int(account_id)
task.lease_id = int(lease.id)
task.operator_id = current.id
task.execution_status = "bound" if already_bound_role else "allocated"
task.next_allocate_at = None
task.binding_status = "bound" if already_bound_role else "not_started"
soft_reasons = cached_state.soft_requirement_reasons(
required_points=required_points
)
gate_status, gate_issue, gate_message = _exchange_gate(
cached_state,
task.commodity_id,
allow_not_open=is_presale,
)
if gate_status:
task.exchange_status = gate_status
task.issue_code = gate_issue
task.last_error = gate_message
elif cached_state.elite_opened is not True:
task.exchange_status = "not_opened"
task.issue_code = "elite_not_opened"
task.last_error = "账号尚未开通精英宝典,可开通后继续"
elif cached_state.points is None or cached_state.points < required_points:
task.exchange_status = "points_short"
task.issue_code = "points_short"
task.last_error = "账号积分不足,可充值后继续"
else:
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
task.updated_at = moment
_apply_task_lease_policy(db, task, lease=lease)
detail: dict[str, Any] = {
"accountId": int(account_id),
"accountName": account_name,
"points": cached_state.points,
"eliteOpened": cached_state.elite_opened,
"softReasons": soft_reasons,
"exchangeStatus": task.exchange_status,
"allocationStrategy": allocation_strategy,
"capabilityObservedAt": _jsonable(observed_at),
"capabilityValidUntil": _jsonable(valid_until),
}
if extra_event_detail:
detail.update(extra_event_detail)
_append_event(
db,
task.id,
"account_allocated",
actor_type="user",
actor_id=current.id,
detail=detail,
)
if already_bound_role:
_append_event(
db,
task.id,
"binding_reused_same_role_account",
detail={
"roleName": already_bound_role[:128],
"accountId": int(account_id),
"accountName": account_name,
"reason": "same_role_existing_account",
},
)
_emit_order_site_binding_state(db, task.id)
if not commit:
return {}
db.commit()
return get_task_detail(db, task.id)
def _account_meets_commodity_eligibility(
db: Session,
*,
account_id: int,
commodity_id: str,
scope: str,
moment: datetime,
allow_before_open: bool,
) -> AccountCommodityState | None:
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
allowed_offers = (
(OFFER_STATE_ACTIVE, OFFER_STATE_BEFORE)
if allow_before_open
else (OFFER_STATE_ACTIVE,)
)
return (
db.query(AccountCommodityState)
.filter(
AccountCommodityState.account_id == int(account_id),
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
AccountCommodityState.account_eligibility == "eligible",
AccountCommodityState.offer_state.in_(allowed_offers),
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
or_(
AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at < since,
),
)
.first()
)
def _find_reusable_same_role_target(
db: Session,
*,
task: PlatformFulfillmentTask,
role: str,
policy: dict[str, Any],
required_co: tuple[str, ...],
moment: datetime,
preferred_account_ids: tuple[int, ...] = (),
) -> dict[str, Any] | None:
"""查找可与当前订单同客户角色合并/复用的目标斗鱼账号(不改动当前订单)。"""
if not policy.get("sameRoleReuseEnabled", True) or not role:
return None
scope = task.scope or SCOPE_ELITE
since_365 = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
sibling_rows = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN,
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.account_id.isnot(None),
PlatformFulfillmentTask.execution_status != "cancelled",
func.lower(func.trim(PlatformFulfillmentTask.customer_role_name))
== role.casefold(),
)
.order_by(
case((PlatformFulfillmentTask.lease_id.isnot(None), 0), else_=1),
case((PlatformFulfillmentTask.binding_status == "bound", 0), else_=1),
PlatformFulfillmentTask.updated_at.desc(),
PlatformFulfillmentTask.id.desc(),
)
.limit(10)
.all()
)
candidate_account_ids: list[int] = []
for preferred_id in preferred_account_ids:
if preferred_id and int(preferred_id) not in candidate_account_ids:
candidate_account_ids.append(int(preferred_id))
for row in sibling_rows:
if row.account_id and int(row.account_id) not in candidate_account_ids:
candidate_account_ids.append(int(row.account_id))
role_lock = find_role_lock(db, role, current_account_id=None, now=moment)
if role_lock is not None and int(role_lock.account_id) not in candidate_account_ids:
candidate_account_ids.append(int(role_lock.account_id))
if not candidate_account_ids:
return None
current_account_id = int(task.account_id) if task.account_id else 0
for candidate_account_id in candidate_account_ids:
if current_account_id and int(candidate_account_id) == current_account_id:
continue
account = db.get(Account, int(candidate_account_id))
if account is None:
continue
if (
not bool(account.auto_managed)
or str(account.status or "") in MANUAL_STATES
or not str(account.cookie or "").strip()
or str(account.ck_check_status or "") != "valid"
or account.assigned_to is not None
):
continue
account_role = str(account.game_name or "").strip()
if str(account.role_bind_status or "") == "bound" and (
not account_role or not role_names_match(account_role, role)
):
continue
if find_account_lock(db, account.id, role, now=moment) is not None:
continue
# 同一斗鱼号不能用来兑换两次完全相同的商品。
duplicate_commodity = (
db.query(PlatformFulfillmentTask.id)
.filter(
PlatformFulfillmentTask.account_id == int(account.id),
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.execution_status != "cancelled",
PlatformFulfillmentTask.commodity_id == task.commodity_id,
)
.first()
)
if duplicate_commodity is not None:
continue
primary_state = _account_meets_commodity_eligibility(
db,
account_id=int(account.id),
commodity_id=task.commodity_id,
scope=scope,
moment=moment,
allow_before_open=is_presale,
)
if primary_state is None:
continue
co_missing = any(
_account_meets_commodity_eligibility(
db,
account_id=int(account.id),
commodity_id=co_cid,
scope=scope,
moment=moment,
allow_before_open=True,
)
is None
for co_cid in required_co
)
if co_missing:
continue
recent_exchange = (
db.query(AccountEvent.id)
.filter(
AccountEvent.account_id == int(account.id),
AccountEvent.event_type == "exchange",
AccountEvent.subject_key.in_([task.commodity_id, *required_co]),
AccountEvent.occurred_at >= since_365,
)
.first()
)
if recent_exchange is not None:
continue
active_collab = active_collab_order_for_account(db, int(account.id))
if active_collab is not None:
collab_role = str(active_collab.bind_game_role or "").strip()
if not collab_role and active_collab.source_task_id:
source_task = db.get(
PlatformFulfillmentTask, int(active_collab.source_task_id)
)
if source_task is not None:
collab_role = str(source_task.customer_role_name or "").strip()
if not collab_role or not role_names_match(collab_role, role):
continue
active_lease = (
db.query(AccountLease)
.filter(
AccountLease.account_id == int(account.id),
AccountLease.status == "active",
)
.with_for_update()
.first()
)
reused_existing_lease = False
sibling_ids: list[int] = []
sibling_bound = False
has_active_qr_sibling = False
earliest_sibling_id: int | None = None
if active_lease is not None:
if active_lease.purpose != "platform_fulfillment":
continue
holders = (
db.query(PlatformFulfillmentTask)
.filter(
PlatformFulfillmentTask.lease_id == int(active_lease.id),
PlatformFulfillmentTask.execution_status != "cancelled",
)
.all()
)
if not holders:
continue
if any(
not str(holder.customer_role_name or "").strip()
or not role_names_match(holder.customer_role_name, role)
or holder.commodity_id == task.commodity_id
for holder in holders
):
continue
reused_existing_lease = True
sibling_ids = [int(holder.id) for holder in holders]
sibling_bound = any(holder.binding_status == "bound" for holder in holders)
has_active_qr_sibling = any(
holder.binding_status
in {
"preparing",
"qr_pending",
"waiting_bind",
"role_ready",
"confirming",
}
for holder in holders
)
earliest_sibling_id = min(sibling_ids)
elif active_collab is not None:
continue
else:
acc_siblings = [
row
for row in sibling_rows
if int(row.account_id or 0) == int(account.id)
]
if acc_siblings:
sibling_bound = any(
row.binding_status == "bound" for row in acc_siblings
)
earliest_sibling_id = min(int(row.id) for row in acc_siblings)
role_lock_matches = bool(
role_lock is not None and int(role_lock.account_id) == int(account.id)
)
already_bound_role = ""
if sibling_bound:
already_bound_role = account_role or role
elif (
str(account.role_bind_status or "") == "bound"
and account_role
and role_names_match(account_role, role)
and role_lock_matches
):
already_bound_role = account_role
return {
"account": account,
"primary_state": primary_state,
"active_lease": active_lease,
"reused_existing_lease": reused_existing_lease,
"sibling_ids": sibling_ids,
"sibling_bound": sibling_bound,
"has_active_qr_sibling": has_active_qr_sibling,
"earliest_sibling_id": earliest_sibling_id,
"role_lock_matches": role_lock_matches,
"already_bound_role": already_bound_role,
}
return None
def _attach_task_to_same_role_target(
db: Session,
*,
task: PlatformFulfillmentTask,
target: dict[str, Any],
role: str,
current: User,
moment: datetime,
extra_event_detail: dict[str, Any] | None = None,
commit: bool = True,
) -> dict[str, Any] | None:
account: Account = target["account"]
primary_state: AccountCommodityState = target["primary_state"]
lease: AccountLease | None = target["active_lease"]
reused_existing_lease: bool = bool(target["reused_existing_lease"])
sibling_ids: list[int] = list(target["sibling_ids"])
already_bound_role: str = str(target["already_bound_role"] or "")
if lease is None:
candidate_model = AccountCandidate(
account_id=int(account.id),
username=str(account.username or ""),
nickname=str(account.nickname or ""),
points=int(account.points or 0),
gold_balance=account.gold_balance,
points_expire_at=account.points_expire_at,
role_change_available_at=account.role_change_available_at,
)
lease = lease_account(
db,
candidate=candidate_model,
holder_user_id=current.id,
task_id=task.id,
commodity_id=task.commodity_id,
ttl_minutes=_lease_duration_minutes(db),
commit=False,
)
if lease is None:
return None
account_name = account.nickname or account.username or f"#{account.id}"
availability = allocation_availability(
primary_state.account_eligibility,
primary_state.offer_state,
)
cached_state = DouyuLiveAccountState(
account_id=int(account.id),
account_name=account_name,
checked_at=primary_state.observed_at or moment,
ck_verdict="valid",
ck_message="同角色复用关联账号 CK 有效",
elite_opened=account.elite_opened,
points=account.points,
limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at,
commodity_availability={task.commodity_id: availability},
commodity_blocking_reasons=(
{task.commodity_id: str(primary_state.blocking_reason or "")}
if primary_state.blocking_reason
else {}
),
)
merged_detail = {
"sharedLease": reused_existing_lease,
"siblingTaskIds": sibling_ids,
"reusedRoleName": role,
}
if extra_event_detail:
merged_detail.update(extra_event_detail)
return _apply_allocated_account_state(
db,
task=task,
account_id=int(account.id),
account_name=account_name,
lease=lease,
cached_state=cached_state,
required_points=int(task.required_points or 0),
is_presale=classification.normalize_sale_mode(task.sale_mode) == "presale",
current=current,
moment=moment,
allocation_strategy="same_role_reuse",
observed_at=primary_state.observed_at,
valid_until=primary_state.valid_until,
extra_event_detail=merged_detail,
already_bound_role=already_bound_role,
commit=commit,
)
def _try_reuse_same_role_account(
db: Session,
*,
task: PlatformFulfillmentTask,
current: User,
policy: dict[str, Any],
required_co: tuple[str, ...],
moment: datetime,
) -> dict[str, Any] | None:
"""同客户角色多单时,优先复用已分配/已绑定的同一斗鱼账号,避免撞 7 天角色锁。"""
role = str(task.customer_role_name or "").strip()
target = _find_reusable_same_role_target(
db,
task=task,
role=role,
policy=policy,
required_co=required_co,
moment=moment,
)
if target is None:
return None
return _attach_task_to_same_role_target(
db,
task=task,
target=target,
role=role,
current=current,
moment=moment,
commit=True,
)
def try_reallocate_task_to_same_role(
db: Session,
*,
task: PlatformFulfillmentTask,
current: User,
role_name: str = "",
trigger: str = "role_sync",
preferred_account_id: int | None = None,
allow_pending_role_ready: bool = False,
commit: bool = False,
now: datetime | None = None,
) -> bool:
"""晚提交角色资料或发现同角色已绑他号时,把尚未绑定完成的任务合并到同角色账号。"""
if (
task.flow_version != FLOW_VERSION_CLEAN
or task.execution_status in {"completed", "cancelled"}
or not task.commodity_id
):
return False
allowed_binding_statuses = {
"not_started",
"preparing",
"qr_pending",
"waiting_bind",
}
if allow_pending_role_ready:
allowed_binding_statuses.add("role_ready")
if str(task.binding_status or "") not in allowed_binding_statuses:
return False
role = str(role_name or task.customer_role_name or "").strip()
if not role:
return False
task_role = str(task.customer_role_name or "").strip()
if task_role and not role_names_match(task_role, role):
return False
moment = now or _now()
policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy"))
required_co, _preferred_co = bundle_requirements_for_commodity(
task.commodity_id, policy
)
preferred_ids = (int(preferred_account_id),) if preferred_account_id else ()
target = _find_reusable_same_role_target(
db,
task=task,
role=role,
policy=policy,
required_co=required_co,
moment=moment,
preferred_account_ids=preferred_ids,
)
if target is None:
return False
if task.account_id is not None:
target_is_bound = bool(
target["already_bound_role"]
or target["sibling_bound"]
or target["role_lock_matches"]
)
if not target_is_bound:
if str(task.binding_status or "") != "not_started":
return False
earliest_sibling_id = target["earliest_sibling_id"]
if not target["has_active_qr_sibling"] and (
earliest_sibling_id is None or int(earliest_sibling_id) >= int(task.id)
):
return False
from .lifecycle import _release_or_detach_shared_lease
old_account_id = int(task.account_id)
old_lease = (
db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first()
if task.lease_id
else None
)
_release_or_detach_shared_lease(
db,
task=task,
lease=old_lease,
current=current,
collab_reason=f"same_role_merge:{trigger}",
release_reason=f"same_role_merge:{trigger}",
)
if task.bind_task_id:
old_bind = db.get(DouyuTask, int(task.bind_task_id))
if old_bind is not None and old_bind.status in {
"planned",
"pending",
"running",
}:
shared_bind = (
db.query(PlatformFulfillmentTask.id)
.filter(
PlatformFulfillmentTask.bind_task_id == int(old_bind.id),
PlatformFulfillmentTask.id != int(task.id),
PlatformFulfillmentTask.execution_status != "cancelled",
)
.first()
)
if shared_bind is None:
old_bind.status = "stopped"
old_bind.message = "同角色已改用原绑定账号,终止旧绑码任务"
old_bind.finished_at = moment
old_bind.queue_lane = ""
old_bind.next_run_at = None
task.account_id = None
task.lease_id = None
task.bind_task_id = None
task.execution_status = "ready"
task.binding_status = "not_started"
task.exchange_status = "not_started"
task.issue_code = ""
task.last_error = ""
_append_event(
db,
task.id,
"account_released",
actor_type="system",
detail={
"reason": f"same_role_merge:{trigger}",
"previousAccountId": old_account_id,
"targetAccountId": int(target["account"].id),
},
)
extra_detail = {
"mergedFromAccountId": old_account_id,
"mergeTrigger": trigger,
}
else:
extra_detail = {"mergeTrigger": trigger}
attached = _attach_task_to_same_role_target(
db,
task=task,
target=target,
role=role,
current=current,
moment=moment,
extra_event_detail=extra_detail,
commit=commit,
)
return attached is not None
def _allocate_task_from_capability(
db: Session,
*,
task: PlatformFulfillmentTask,
current: User,
) -> dict[str, Any]:
"""只用本地能力索引选号;外部资格查询留给独立同步队列。"""
# 同一任务并发点击/调度重试时,先在任务行上加锁。否则两个请求会各自
# 领到一个账号租约,后提交的一方覆盖 task.lease_id,先前的 active 租约
# 就变成孤儿(生产 7482/8877 就是这么来的)。
task = _load_task_for_update(db, int(task.id))
if task.account_id and task.lease_id:
current_lease = (
db.query(AccountLease).filter(AccountLease.id == int(task.lease_id)).first()
)
if current_lease is not None and current_lease.status == "active":
return get_task_detail(db, task.id)
moment = _now()
required_points = int(task.required_points or 0)
policy = normalize_allocation_policy(get_settings(db).get("allocationPolicy"))
required_co, preferred_co = bundle_requirements_for_commodity(
policy,
task.commodity_id,
)
protected_co = protected_bundle_commodities(policy, task.commodity_id)
priority_order = policy.get("priorityOrder") or ()
reused = _try_reuse_same_role_account(
db,
task=task,
current=current,
policy=policy,
required_co=required_co,
moment=moment,
)
if reused is not None:
return reused
try:
candidate_limit = int(
os.getenv(
"PLATFORM_FULFILLMENT_CAPABILITY_CANDIDATE_LIMIT",
str(DEFAULT_CAPABILITY_CANDIDATE_LIMIT),
)
)
except ValueError:
candidate_limit = DEFAULT_CAPABILITY_CANDIDATE_LIMIT
candidate_limit = max(1, min(candidate_limit, 100))
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
capability_candidates = capability_candidate_rows(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE,
now=moment,
allow_before_open=is_presale,
required_co_commodities=required_co,
preferred_co_commodities=preferred_co,
protected_bundle_commodities=protected_co,
priority_order=priority_order,
)
recent_exchange_ids: set[int] = set()
if capability_candidates:
candidate_ids = [int(item.account.id) for item in capability_candidates]
since = moment - timedelta(days=365)
commodity_check_ids = list(dict.fromkeys([task.commodity_id, *required_co]))
recent_exchange_ids = {
int(account_id)
for (account_id,) in (
db.query(AccountEvent.account_id)
.filter(
AccountEvent.account_id.in_(candidate_ids),
AccountEvent.event_type == "exchange",
AccountEvent.subject_key.in_(commodity_check_ids),
AccountEvent.occurred_at >= since,
)
.distinct()
.all()
)
}
diagnostics: list[dict[str, Any]] = []
qualified: list[tuple[CapabilityCandidate, DouyuLiveAccountState]] = []
for candidate in capability_candidates:
account_id = int(candidate.account.id)
if account_id in recent_exchange_ids:
diagnostics.append(
{
"accountId": account_id,
"accountName": candidate.account.nickname
or candidate.account.username,
"reasons": ["365 天内已有该商品或捆绑商品兑换事件"],
"source": "capability",
}
)
continue
qualified.append(
(
candidate,
_cached_capability_state(
candidate,
commodity_id=task.commodity_id,
),
)
)
qualified.sort(
key=lambda item: _candidate_sort_key(
item[0],
item[1],
required_points=required_points,
priority_order=priority_order,
)
)
selected: CapabilityCandidate | None = None
selected_state: DouyuLiveAccountState | None = None
lease = None
lease_duration_minutes = _lease_duration_minutes(db)
for candidate, cached_state in qualified:
account = candidate.account
candidate_model = AccountCandidate(
account_id=int(account.id),
username=str(account.username or ""),
nickname=str(account.nickname or ""),
points=int(cached_state.points or 0),
gold_balance=account.gold_balance,
points_expire_at=account.points_expire_at,
role_change_available_at=account.role_change_available_at,
)
lease = lease_account(
db,
candidate=candidate_model,
holder_user_id=current.id,
task_id=task.id,
commodity_id=task.commodity_id,
ttl_minutes=lease_duration_minutes,
commit=False,
)
if lease is not None:
selected = candidate
selected_state = cached_state
break
diagnostics.append(
{
"accountId": int(account.id),
"accountName": cached_state.account_name,
"reasons": ["账号刚被其他任务占用"],
"source": "capability",
}
)
if selected is None or selected_state is None or lease is None:
availability_counts = _capability_availability_counts(
db,
commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE,
now=moment,
)
retry_at, retry_reason = _local_allocation_retry_at(
db,
task=task,
now=moment,
availability_counts=availability_counts,
lease_conflict=bool(qualified),
)
if (
required_co
and not capability_candidates
and retry_reason == "lease_conflict"
):
retry_reason = "bundle_co_eligibility_missing"
retry_at = moment + timedelta(seconds=LOCAL_STOCK_RETRY_SECONDS)
refresh_queued = (
_seed_capability_refresh(db, task=task, now=moment)
if retry_reason
in {
"capability_cache_miss",
"account_role_cooldown",
"account_pool_busy",
"bundle_co_eligibility_missing",
}
else 0
)
if retry_reason == "commodity_not_open":
task.issue_code = "commodity_not_open"
task.last_error = "该商品尚未到开放时间,已按开放时间安排重新选号"
elif retry_reason == "capability_cache_miss":
task.issue_code = "capability_cache_miss"
task.last_error = "暂无该商品的新鲜账号兑换资格,等待后台刷新"
elif retry_reason == "bundle_co_eligibility_missing":
task.issue_code = "bundle_co_eligibility_missing"
task.last_error = (
"已有单个商品可兑账号,但缺少同时具备捆绑商品全部兑换资格的可用账号"
)
elif retry_reason == "lease_conflict":
task.issue_code = "account_lease_conflict"
task.last_error = "已找到候选账号,但刚被其他任务占用"
elif retry_reason == "account_role_cooldown":
task.issue_code = "account_role_cooldown"
task.last_error = (
"已有具备兑换资格的账号,但都处于斗鱼换绑冷却期;"
"后台正在继续补充未绑定角色的可用账号"
)
elif retry_reason == "account_pool_busy":
task.issue_code = "account_pool_busy"
task.last_error = (
"已有具备兑换资格的账号,但当前被租约或预售台账占用;"
"后台正在继续补充可用账号"
)
else:
task.issue_code = "no_eligible_account"
task.last_error = "本地能力池暂无可用账号"
task.execution_status = "ready"
task.next_allocate_at = retry_at
task.updated_at = moment
_append_event(
db,
task.id,
"account_allocation_failed",
detail={
"candidateCount": len(capability_candidates),
"matchingMode": "capability",
"strategy": "local_capability",
"capabilityCandidates": len(capability_candidates),
"requiredCoCommodities": list(required_co),
"preferredCoCommodities": list(preferred_co),
"availabilityCounts": availability_counts,
"retryAt": _jsonable(retry_at),
"retryReason": retry_reason,
"refreshQueued": refresh_queued,
"diagnostics": diagnostics[:20],
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
selected_account = selected.account
return _apply_allocated_account_state(
db,
task=task,
account_id=int(selected_account.id),
account_name=selected_state.account_name,
lease=lease,
cached_state=selected_state,
required_points=required_points,
is_presale=is_presale,
current=current,
moment=moment,
allocation_strategy="local_capability",
observed_at=selected.state.observed_at,
valid_until=selected.state.valid_until,
extra_event_detail={
"requiredCoCommodities": list(required_co),
"preferredCoCommodities": list(preferred_co),
"bundleMissingCount": int(selected.state.bundle_missing_count or 0),
},
)
def prepare_manual_allocation(
db: Session,
*,
task_id: int,
current: User,
) -> dict[str, Any]:
"""在短请求内完成人工选号校验,并把任务标记为立即可领取。
真正的官网账号检测由后台 auto allocator 执行。这样 API 请求不会在多次外部
HTTP 调用期间一直持有数据库事务,也不会因为重复点击占满连接池。
"""
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
if not task.commodity_id or not task.required_points:
raise HTTPException(status_code=409, detail="请先完成商品映射")
if task.account_id and task.lease_id:
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease and lease.status == "active":
return get_task_detail(db, task.id)
if (
task.execution_status == "manual_required"
and not task.account_id
and not task.lease_id
and task.issue_code in {"binding_failed", "lease_expired", "role_changed"}
):
# 绑定失败账号已释放后,人工触发一次重新选号;
# 客户资料保留,分配成功后 auto allocator 会继续启动绑定。
task.execution_status = "ready"
task.binding_status = "not_started"
task.bind_task_id = None
task.issue_code = ""
task.last_error = ""
task.next_allocate_at = _now()
task.operator_id = current.id
task.updated_at = _now()
task.state_version = int(task.state_version or 0) + 1
_append_event(
db,
task.id,
"binding_retry_requested",
actor_type="user",
actor_id=current.id,
detail={"reason": "manual_reallocate_after_binding_failure"},
)
_emit_order_site_binding_state(db, task.id)
db.flush()
return get_task_detail(db, task.id)
if task.execution_status != "ready":
raise HTTPException(status_code=409, detail="只有待分配任务可以重新选号")
task.next_allocate_at = _now()
task.updated_at = _now()
db.flush()
return get_task_detail(db, task.id)
def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
if not task.commodity_id or not task.required_points:
raise HTTPException(status_code=409, detail="请先完成商品映射")
if task.account_id and task.lease_id:
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease and lease.status == "active":
return get_task_detail(db, task.id)
# 阶段 5:生产选号只允许读取本地能力索引。官网查询由
# account_sync_queue/商品能力补货完成,绑码与兑换前各自实时复核。
return _allocate_task_from_capability(
db,
task=task,
current=current,
)