Avoid automatic allocation of accounts with active external collaboration, require explicit manual takeover of platform leases, and add Douyu account identity search.
548 lines
16 KiB
Python
548 lines
16 KiB
Python
"""直播账号履约的账号筛选与租约。
|
|
|
|
只复用账号池中经过验证的筛选与数据库唯一约束,不引入自动充值、自动兑换
|
|
或多活动 scope。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
from sqlalchemy import case, or_, select
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ...models import (
|
|
Account,
|
|
AccountCommodityState,
|
|
AccountEvent,
|
|
AccountLease,
|
|
DouyuExternalOrder,
|
|
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
|
|
BINDING_LEASE_MINUTES = 120
|
|
EXCHANGE_COOLDOWN_DAYS = 365
|
|
POOL_OWNER_ROLES = ("super_admin", "operation", "support")
|
|
ACTIVE_COLLAB_ORDER_STATUSES = (
|
|
"incomplete",
|
|
"to_recharge",
|
|
"recharged",
|
|
"scripted",
|
|
"points_error",
|
|
"role_error",
|
|
"failed",
|
|
)
|
|
|
|
|
|
@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}"
|
|
|
|
|
|
def _now(now: datetime | None = None) -> datetime:
|
|
return now or datetime.now(UTC)
|
|
|
|
|
|
def _pool_owner_ids():
|
|
return select(User.id).where(
|
|
User.role.in_(POOL_OWNER_ROLES),
|
|
User.is_active.is_(True),
|
|
)
|
|
|
|
|
|
def _active_collab_order():
|
|
"""账号即使缺少协作租约,只要还有活动协作单也不能进入自动选号。"""
|
|
return (
|
|
select(DouyuExternalOrder.id)
|
|
.where(
|
|
DouyuExternalOrder.account_id == Account.id,
|
|
DouyuExternalOrder.archived_at.is_(None),
|
|
DouyuExternalOrder.status.in_(ACTIVE_COLLAB_ORDER_STATUSES),
|
|
)
|
|
.exists()
|
|
)
|
|
|
|
|
|
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)
|
|
owner_ids = _pool_owner_ids()
|
|
active_lease = (
|
|
select(AccountLease.id)
|
|
.where(AccountLease.active_account_id == Account.id)
|
|
.exists()
|
|
)
|
|
active_collab = _active_collab_order()
|
|
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",
|
|
Account.ck_check_status == "valid",
|
|
Account.cookie.isnot(None),
|
|
Account.cookie != "",
|
|
Account.auto_managed.is_(True),
|
|
Account.elite_opened.is_(True),
|
|
Account.points.isnot(None),
|
|
Account.points >= max(0, int(required_points)),
|
|
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
|
|
~active_lease,
|
|
~active_collab,
|
|
~exchanged,
|
|
or_(
|
|
Account.role_change_available_at.is_(None),
|
|
Account.role_change_available_at <= 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 = "",
|
|
) -> list[Account]:
|
|
"""按缓存质量优先排序,但保留实时检测作为最终准入判断。"""
|
|
owner_ids = _pool_owner_ids()
|
|
active_lease = (
|
|
select(AccountLease.id)
|
|
.where(AccountLease.active_account_id == Account.id)
|
|
.exists()
|
|
)
|
|
active_collab = _active_collab_order()
|
|
query = db.query(Account).filter(
|
|
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 <= _now(),
|
|
),
|
|
or_(Account.assigned_to.is_(None), Account.assigned_to.in_(owner_ids)),
|
|
~active_lease,
|
|
~active_collab,
|
|
)
|
|
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)
|
|
return (
|
|
query.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.ck_checked_at.is_(None).desc(),
|
|
Account.ck_checked_at.asc(),
|
|
Account.points.asc(),
|
|
Account.id.asc(),
|
|
)
|
|
.limit(max(1, min(int(limit), 100)))
|
|
.all()
|
|
)
|
|
|
|
|
|
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()
|
|
)
|
|
active_collab = _active_collab_order()
|
|
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,
|
|
~active_collab,
|
|
)
|
|
.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,
|
|
*,
|
|
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,
|
|
) -> 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,
|
|
)
|
|
|
|
|
|
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",
|
|
"acquire_account_lease",
|
|
"active_lease_for_account",
|
|
"capability_candidate_accounts",
|
|
"eligible_accounts",
|
|
"expire_platform_fulfillment_leases",
|
|
"has_recent_exchange",
|
|
"lease_account",
|
|
"live_candidate_accounts",
|
|
"release_lease",
|
|
"renew_lease",
|
|
]
|