feat(fulfillment): 增加账号商品能力索引与生命周期事件

This commit is contained in:
yml
2026-11-18 19:30:59 +08:00
parent dc95d83b32
commit 667634a8df
35 changed files with 3076 additions and 82 deletions
@@ -13,7 +13,14 @@ from sqlalchemy import case, or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ...models import Account, AccountEvent, AccountLease, User
from ...models import Account, AccountCommodityState, AccountEvent, AccountLease, User
from ..account_capability_service import AVAILABILITY_AVAILABLE
from ..account_events_service import (
CATEGORY_OPS,
EVENT_LEASE_ACQUIRED,
EVENT_LEASE_RELEASED,
emit,
)
from ..account_lifecycle import MANUAL_STATES
VALIDATION_LEASE_MINUTES = 5
@@ -136,6 +143,10 @@ def live_candidate_accounts(
Account.cookie != "",
Account.auto_managed.is_(True),
Account.status.notin_(MANUAL_STATES),
or_(
Account.role_change_available_at.is_(None),
Account.role_change_available_at <= _now(),
),
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
~active_lease,
)
@@ -172,6 +183,80 @@ def live_candidate_accounts(
)
def capability_candidate_accounts(
db: Session,
*,
commodity_id: str,
required_points: int = 0,
scope: str = "elite",
limit: int = 20,
now: datetime | None = None,
) -> list[Account]:
"""从新鲜的商品能力索引读取候选账号,不产生外部请求。"""
commodity = commodity_id.strip()
if not commodity:
return []
moment = _now(now)
since = moment - timedelta(days=EXCHANGE_COOLDOWN_DAYS)
owner_ids = _pool_owner_ids()
active_lease = (
select(AccountLease.id)
.where(AccountLease.active_account_id == Account.id)
.exists()
)
return (
db.query(Account)
.join(
AccountCommodityState,
AccountCommodityState.account_id == Account.id,
)
.filter(
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity,
AccountCommodityState.availability == AVAILABILITY_AVAILABLE,
AccountCommodityState.valid_until.isnot(None),
AccountCommodityState.valid_until > moment,
or_(
AccountCommodityState.available_from.is_(None),
AccountCommodityState.available_from <= moment,
),
or_(
AccountCommodityState.available_until.is_(None),
AccountCommodityState.available_until >= moment,
),
or_(
AccountCommodityState.last_exchange_at.is_(None),
AccountCommodityState.last_exchange_at < since,
),
Account.cookie.isnot(None),
Account.cookie != "",
Account.auto_managed.is_(True),
Account.status.notin_(MANUAL_STATES),
or_(
Account.role_change_available_at.is_(None),
Account.role_change_available_at <= moment,
),
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
~active_lease,
)
.order_by(
case((Account.ck_check_status == "valid", 0), else_=1),
case((Account.status == "active", 0), else_=1),
case((Account.elite_opened.is_(True), 0), else_=1),
case(
(Account.points >= max(0, int(required_points)), 0),
else_=1,
),
Account.points.asc(),
AccountCommodityState.observed_at.desc(),
Account.id.asc(),
)
.limit(max(1, min(int(limit), 100)))
.all()
)
def has_recent_exchange(
db: Session,
*,
@@ -231,6 +316,26 @@ def lease_account(
if lease in db:
db.expunge(lease)
return None
emit(
db,
account_id=int(candidate.account_id),
event_type=EVENT_LEASE_ACQUIRED,
title=f"履约占用:任务 #{task_id}",
category=CATEGORY_OPS,
detail={
"lease_id": lease.id,
"task_id": task_id,
"holder_user_id": holder_user_id,
"commodity_id": commodity_id,
"purpose": "platform_fulfillment",
},
source="lease",
subject_type="task",
subject_key=str(task_id),
actor_type="user",
actor_id=holder_user_id,
source_ref=f"account_lease_acquired:{lease.id}",
)
db.commit()
return lease
@@ -265,6 +370,23 @@ def release_lease(
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}",
)
db.commit()
return True
@@ -292,6 +414,24 @@ def expire_platform_fulfillment_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)
@@ -302,6 +442,7 @@ __all__ = [
"EXCHANGE_COOLDOWN_DAYS",
"VALIDATION_LEASE_MINUTES",
"AccountCandidate",
"capability_candidate_accounts",
"eligible_accounts",
"expire_platform_fulfillment_leases",
"has_recent_exchange",
@@ -116,7 +116,7 @@ def run_auto_allocation_once(
)
candidates = (
query.order_by(
PlatformFulfillmentTask.next_allocate_at.asc(),
PlatformFulfillmentTask.paid_at.asc(),
PlatformFulfillmentTask.id.asc(),
)
.limit(batch_size)
@@ -10,6 +10,7 @@ from threading import Lock
from typing import Any
from fastapi import HTTPException
from loguru import logger
from sqlalchemy import or_
from sqlalchemy.orm import Session
@@ -28,6 +29,12 @@ from ..account_binding import (
binding_role_from_result,
pending_binding_role_from_result,
)
from ..account_capability_service import (
AVAILABILITY_AVAILABLE,
AVAILABILITY_LIMITED,
record_account_commodity_state,
)
from ..business_events import record_account_query, record_douyu_task_started
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state
from ..douyu_activity_query import activity_client, query_exchange_eligibility
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
@@ -39,6 +46,7 @@ from ..external_order_source import (
)
from .account_selector import (
AccountCandidate,
capability_candidate_accounts,
has_recent_exchange,
lease_account,
live_candidate_accounts,
@@ -63,6 +71,11 @@ BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "600")
AUTO_SYNC_INTERVAL_SECONDS = 900.0
DEFAULT_LIVE_CANDIDATE_LIMIT = 20
def _matching_mode() -> str:
mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower()
return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid"
_SYNC_LOCK = Lock()
_AUTO_SYNC_LOCK = Lock()
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
@@ -237,6 +250,7 @@ def _upsert_order_snapshot(
task.source_snapshot_json = _jsonable(snapshot)
return task, created, False
previous_execution_status = task.execution_status
terminal = (
terminal_order
or _snapshot_value(
@@ -331,10 +345,22 @@ def _upsert_order_snapshot(
task.last_error = "订单已关闭或直播履约配置已停用"
task.next_allocate_at = None
else:
_apply_mapping(task, mapping)
if task.execution_status == "ready" and task.account_id is None:
task.next_allocate_at = _now()
elif task.account_id is not None:
# 订单快照会被重复投递。只有未分配任务从「待映射」进入「待分配」时
# 才允许改生命周期状态;已分配任务不能被快照更新打回 pending。
update_execution_status = task.account_id is None and (
previous_execution_status == "pending_mapping" or mapping is None
)
_apply_mapping(
task,
mapping,
update_execution_status=update_execution_status,
)
if task.account_id is not None:
task.next_allocate_at = None
elif task.execution_status == "ready":
if previous_execution_status != "ready" or task.next_allocate_at is None:
task.next_allocate_at = _now()
else:
task.next_allocate_at = None
after = (
@@ -662,18 +688,24 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
def _apply_mapping(
task: PlatformFulfillmentTask,
mapping: PlatformCommodityMapping | None,
*,
update_execution_status: bool = True,
) -> None:
if mapping is None:
if mapping is not None:
task.commodity_mapping_id = mapping.id
task.commodity_id = mapping.commodity_id
task.required_points = mapping.required_points
else:
task.commodity_mapping_id = None
task.commodity_id = ""
task.required_points = None
if not update_execution_status:
return
if mapping is None:
task.execution_status = "pending_mapping"
task.issue_code = "mapping_missing"
task.last_error = "内部 SKU 尚未配置斗鱼商品映射"
return
task.commodity_mapping_id = mapping.id
task.commodity_id = mapping.commodity_id
task.required_points = mapping.required_points
task.execution_status = "ready"
task.issue_code = ""
task.last_error = ""
@@ -780,7 +812,10 @@ def _sync_pending_tasks(
task.scope = SCOPE_ELITE
task.source_snapshot_json = _jsonable(row)
task.updated_at = _now()
if task.execution_status in {"pending_mapping", "ready"}:
if (
task.account_id is None
and task.execution_status in {"pending_mapping", "ready"}
):
_apply_mapping(task, mapping)
if task.execution_status == "ready" and task.account_id is None:
task.next_allocate_at = _now()
@@ -1262,6 +1297,7 @@ def upsert_mapping(
pending = db.query(PlatformFulfillmentTask).filter(
PlatformFulfillmentTask.internal_sku_key == sku_key,
PlatformFulfillmentTask.account_id.is_(None),
PlatformFulfillmentTask.execution_status.in_(
["pending_mapping", "ready", "manual_required"]
),
@@ -1324,19 +1360,39 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
except ValueError:
candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT
candidate_limit = max(1, min(candidate_limit, 100))
# 缓存用于优先排序,最终是否可用仍由下面的逐个实时检测决定。
candidates = live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
mode = _matching_mode()
capability_candidates = (
capability_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE,
)
if mode in {"hybrid", "capability"}
else []
)
capability_first = bool(capability_candidates)
candidates = capability_candidates
if not candidates and mode != "capability":
# hybrid 模式下能力索引为空或全部过期时,保留旧逻辑兜底。
candidates = live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
)
diagnostics: list[dict[str, Any]] = []
qualified: list[tuple[Account, DouyuLiveAccountState]] = []
selected: AccountCandidate | None = None
selected_state: DouyuLiveAccountState | None = None
lease = None
for account in candidates:
def inspect_candidate(
account: Account,
*,
source: str,
) -> tuple[Account, DouyuLiveAccountState] | None:
live_state = refresh_douyu_account_state(
db,
account,
@@ -1344,13 +1400,40 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
rid=rid,
act_alias=act_alias,
)
reasons = live_state.blocking_reasons(commodity_id=task.commodity_id)
if has_recent_exchange(
limited = task.commodity_id in live_state.limited_ids
recent_exchange = has_recent_exchange(
db,
account_id=int(account.id),
commodity_id=task.commodity_id,
):
)
reasons = live_state.blocking_reasons(commodity_id=task.commodity_id)
if recent_exchange:
reasons.append("365 天内已有该商品兑换事件")
if live_state.ck_verdict == "valid" and not live_state.error:
try:
record_account_commodity_state(
db,
account,
commodity_id=task.commodity_id,
availability=(
AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE
),
blocking_reason=(
"该账号已达此商品兑换上限" if limited else ""
),
raw_status="1" if limited else "0",
observed_at=live_state.checked_at,
source="live_check",
scope=task.scope or SCOPE_ELITE,
)
except Exception as exc: # noqa: BLE001 - 派生索引不能阻止本次选号
logger.warning(
"写入选号商品能力失败 account_id={} commodity_id={}: {}",
account.id,
task.commodity_id,
exc,
)
if reasons:
diagnostics.append(
{
@@ -1360,10 +1443,45 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": reasons,
"source": source,
}
)
continue
qualified.append((account, live_state))
return None
return account, live_state
def inspect_batch(
batch: list[Account],
*,
source: str,
) -> None:
# 能力索引已按成本排序,首个确认通过即可;旧兜底最多比较 3 个。
for account in batch:
inspected = inspect_candidate(account, source=source)
if inspected is None:
continue
qualified.append(inspected)
if source == "capability" or len(qualified) >= 3:
return
if capability_candidates:
inspect_batch(capability_candidates, source="capability")
elif mode != "capability":
inspect_batch(candidates, source="live")
if not qualified and capability_first and mode == "hybrid":
checked_ids = {int(account.id) for account in capability_candidates}
fallback_candidates = [
account
for account in live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
)
if int(account.id) not in checked_ids
]
candidates = [*candidates, *fallback_candidates]
inspect_batch(fallback_candidates, source="live_fallback")
# 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号,
# 其次是只需充值、只需开通、两者都需要的账号。
@@ -1404,6 +1522,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": ["账号刚被其他任务占用"],
"source": "capability" if capability_first else "live",
}
)
if selected is None or selected_state is None or lease is None:
@@ -1411,7 +1530,11 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
task.next_allocate_at = _now() + timedelta(seconds=45)
task.issue_code = "no_eligible_account"
if not candidates:
task.last_error = "没有带 CK、允许自动管理且未停用的斗鱼账号"
task.last_error = (
"商品能力池暂无可用账号"
if mode == "capability"
else "没有带 CK、允许自动管理且未停用的斗鱼账号"
)
else:
summary = ";".join(
f"{item['accountName']}: {', '.join(item['reasons'][:3])}"
@@ -1428,6 +1551,8 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
"account_allocation_failed",
detail={
"candidateCount": len(candidates),
"matchingMode": mode,
"capabilityCandidates": len(capability_candidates),
"diagnostics": diagnostics,
},
)
@@ -1644,6 +1769,17 @@ async def start_binding(
)
db.add(bind_task)
db.flush()
account = db.query(Account).filter(Account.id == task.account_id).first()
if account is not None:
record_douyu_task_started(
db,
account,
task_id=int(bind_task.id),
task_type="get_bind_qr",
task_label="获取绑定二维码",
scope="elite",
actor_id=current.id,
)
task.bind_task_id = bind_task.id
task.binding_status = "preparing"
task.execution_status = "waiting_bind"
@@ -1855,6 +1991,17 @@ async def confirm_binding(
)
db.add(confirm_task)
db.flush()
account = db.query(Account).filter(Account.id == task.account_id).first()
if account is not None:
record_douyu_task_started(
db,
account,
task_id=int(confirm_task.id),
task_type="confirm_bind",
task_label="确认绑定",
scope="elite",
actor_id=current.id,
)
task.bind_task_id = confirm_task.id
task.binding_status = "confirming"
task.execution_status = "binding_confirming"
@@ -1903,6 +2050,15 @@ def refresh_exchange_eligibility(
account.elite_opened = bool(eligibility.elite_user_info.get("manual_type"))
account.points = eligibility.points
except Exception as exc: # noqa: BLE001 外部接口错误要落成可重试的检查失败
record_account_query(
db,
account,
query_type="exchange_eligibility",
title="刷新兑换资格",
ok=False,
detail={"error": str(exc)[:1000], "commodity_id": task.commodity_id},
actor_id=current.id,
)
task.execution_status = "manual_required"
task.exchange_status = "check_failed"
task.issue_code = "eligibility_check_failed"
@@ -1936,6 +2092,40 @@ def refresh_exchange_eligibility(
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
record_account_commodity_state(
db,
account,
commodity_id=task.commodity_id,
availability=(
AVAILABILITY_LIMITED
if task.commodity_id in eligibility.limited_ids
else AVAILABILITY_AVAILABLE
),
blocking_reason=(
"该账号已达此商品兑换上限"
if task.commodity_id in eligibility.limited_ids
else ""
),
raw_status="1" if task.commodity_id in eligibility.limited_ids else "0",
observed_at=_now(),
source="eligibility_check",
scope=task.scope or SCOPE_ELITE,
)
record_account_query(
db,
account,
query_type="exchange_eligibility",
title="刷新兑换资格",
ok=True,
detail={
"commodity_id": task.commodity_id,
"exchange_status": task.exchange_status,
"limited": task.commodity_id in eligibility.limited_ids,
"points": account.points,
"elite_opened": account.elite_opened,
},
actor_id=current.id,
)
# 积分不足、未开通和限兑都不是流程终点:角色已经绑定,账号继续保留,
# 后续充值/开通/解除限兑后刷新资格即可。
task.execution_status = "bound"