fix(douyu): 补全账号能力目录并回收失效租约

This commit is contained in:
yml
2026-11-22 20:36:40 +08:00
parent 1906f924bc
commit af05c54c3f
18 changed files with 839 additions and 121 deletions
@@ -9,7 +9,7 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from sqlalchemy import case, or_, select
from sqlalchemy import and_, case, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
@@ -18,6 +18,7 @@ from ...models import (
AccountCommodityState,
AccountEvent,
AccountLease,
AccountSyncState,
)
from ..account_capability_service import OFFER_STATE_ACTIVE
from ..account_events_service import (
@@ -36,6 +37,8 @@ from ..account_query_filters import (
role_change_ready_filter,
valid_ck_filter,
)
from ..account_sync_runner import WORK_STOREHOME_SYNC
from ..account_work_queue import active_account_work_exists
VALIDATION_LEASE_MINUTES = 5
BINDING_LEASE_MINUTES = 120
@@ -343,6 +346,96 @@ def capability_candidate_accounts(
]
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()
)
refresh_needed = []
for commodity_id in commodities:
state_exists = (
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
)
.exists()
)
state_due = (
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
or_(
AccountCommodityState.valid_until.is_(None),
AccountCommodityState.valid_until <= moment,
AccountCommodityState.next_check_at.is_(None),
AccountCommodityState.next_check_at <= moment,
),
)
.exists()
)
refresh_needed.append(
or_(
and_(~fresh_storehome, ~state_exists),
state_due,
)
)
return (
db.query(Account)
.filter(
or_(*refresh_needed),
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
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(),
)
.limit(max(1, min(int(limit), 100)))
.all()
)
def has_recent_exchange(
db: Session,
*,
@@ -590,6 +683,7 @@ __all__ = [
"acquire_account_lease",
"active_lease_for_account",
"capability_candidate_accounts",
"capability_refresh_candidate_accounts",
"eligible_accounts",
"expire_platform_fulfillment_leases",
"has_recent_exchange",
@@ -11,7 +11,7 @@ from typing import Any
from fastapi import HTTPException
from loguru import logger
from sqlalchemy import func, or_
from sqlalchemy import func, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from starlette.concurrency import run_in_threadpool
@@ -43,6 +43,7 @@ from ..account_capability_service import (
AVAILABILITY_LIMITED,
AVAILABILITY_NOT_OFFERED,
AVAILABILITY_NOT_OPEN,
OFFER_STATE_ACTIVE,
OFFER_STATE_BEFORE,
OFFER_STATE_NOT_OFFERED,
OFFER_STATE_UNKNOWN,
@@ -53,14 +54,19 @@ from ..account_capability_service import (
record_account_commodity_state,
)
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 WORK_STOREHOME_SYNC
from ..account_work_queue import enqueue_account_work
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 ..business_events import record_account_query, record_douyu_task_started
from ..douyu_account_probe import (
CAPABILITY_OK,
@@ -87,6 +93,7 @@ from .account_selector import (
CapabilityCandidate,
capability_candidate_accounts,
capability_candidate_rows,
capability_refresh_candidate_accounts,
has_recent_exchange,
lease_account,
live_candidate_accounts,
@@ -114,6 +121,21 @@ DEFAULT_LIVE_CANDIDATE_LIMIT = 20
LOCAL_STOCK_RETRY_SECONDS = 5 * 60
LOCAL_CACHE_MISS_RETRY_SECONDS = 2 * 60
LOCAL_LEASE_CONFLICT_RETRY_SECONDS = 5
DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES = 120
def binding_failed_lease_ttl_minutes() -> int:
"""扫码超时任务的账号保留时间;过期后允许重新进入选号池。"""
try:
value = int(
os.getenv(
"PLATFORM_BINDING_FAILED_LEASE_TTL_MINUTES",
str(DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES),
)
)
except ValueError:
return DEFAULT_BINDING_FAILED_LEASE_TTL_MINUTES
return max(1, value)
def _matching_mode() -> str:
@@ -610,6 +632,11 @@ def _lease_policy_for_task(
if status == "cancelled":
return "cancelled", 0
if status == "manual_required":
if task.issue_code == "binding_failed":
return (
"binding_failed_cleanup",
binding_failed_lease_ttl_minutes(),
)
return (
"manual_required",
settings.get("manualRequiredLeaseTtlMinutes"),
@@ -2364,7 +2391,7 @@ def _capability_availability_counts(
commodity_id: str,
scope: str,
now: datetime,
) -> dict[str, int]:
) -> dict[str, Any]:
base = db.query(AccountCommodityState).filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == scope,
@@ -2404,6 +2431,47 @@ def _capability_availability_counts(
.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)
@@ -2411,6 +2479,13 @@ def _capability_availability_counts(
},
**{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),
}
@@ -2444,9 +2519,27 @@ def _local_allocation_retry_at(
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"
if availability_counts:
if availability_counts.get("eligibility:eligible"):
return now + timedelta(seconds=LOCAL_LEASE_CONFLICT_RETRY_SECONDS), "lease_conflict"
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"
@@ -2457,7 +2550,7 @@ def _seed_capability_refresh(
task: PlatformFulfillmentTask,
now: datetime,
) -> int:
"""能力池缺失时只入队独立同步槽,不在分配线程里请求官网。"""
"""能力池不足时只入队独立同步槽,不在分配线程里请求官网。"""
try:
seed_limit = int(
os.getenv("PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT", "20")
@@ -2465,44 +2558,31 @@ def _seed_capability_refresh(
except ValueError:
seed_limit = 20
seed_limit = max(1, min(seed_limit, 100))
account_ids = [
int(account_id)
for (account_id,) in (
db.query(AccountCommodityState.account_id)
.join(Account, Account.id == AccountCommodityState.account_id)
.filter(
AccountCommodityState.platform == TARGET_PLATFORM,
AccountCommodityState.scope == (task.scope or SCOPE_ELITE),
AccountCommodityState.commodity_id == task.commodity_id,
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
~active_lease_exists(),
)
.order_by(
AccountCommodityState.observed_at.is_(None).desc(),
AccountCommodityState.observed_at.asc(),
AccountCommodityState.account_id.asc(),
)
.limit(seed_limit)
.all()
try:
target_pending = max(
1,
int(os.getenv("ACCOUNT_SYNC_QUEUE_TARGET_PENDING", "60")),
)
]
if not account_ids:
account_ids = [
int(account.id)
for account in live_candidate_accounts(
db,
limit=seed_limit,
required_points=int(task.required_points or 0),
commodity_id=task.commodity_id,
)
]
for account_id in dict.fromkeys(account_ids):
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=account_id,
account_id=int(account.id),
work_type=WORK_STOREHOME_SYNC,
priority=20,
due_at=now,
@@ -2512,7 +2592,7 @@ def _seed_capability_refresh(
"platform_task_id": int(task.id),
},
)
return len(set(account_ids))
return len(accounts)
def _allocate_task_from_capability(
@@ -2649,7 +2729,12 @@ def _allocate_task_from_capability(
)
refresh_queued = (
_seed_capability_refresh(db, task=task, now=moment)
if retry_reason == "capability_cache_miss"
if retry_reason
in {
"capability_cache_miss",
"account_role_cooldown",
"account_pool_busy",
}
else 0
)
if retry_reason == "commodity_not_open":
@@ -2661,6 +2746,18 @@ def _allocate_task_from_capability(
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 = "本地能力池暂无可用账号"
@@ -4121,6 +4218,7 @@ def release_task_to_manual(
__all__ = [
"allocate_task",
"archive_mapping",
"binding_failed_lease_ttl_minutes",
"cancel_task",
"complete_manual_exchange",
"confirm_binding",