fix(douyu): 统一外部协作账号租约

This commit is contained in:
yml
2026-11-19 16:03:17 +08:00
parent acd27bde67
commit dd48175b4a
8 changed files with 1248 additions and 79 deletions
+424 -6
View File
@@ -25,6 +25,7 @@ from core.douyu import DouyuActivityClient
from ..models import (
Account,
AccountLease,
AuditLog,
DouyuCollabGift,
DouyuCollabShop,
@@ -38,7 +39,12 @@ from ..models import (
User,
)
from .account_binding import binding_channel, binding_role_from_result
from .account_events_service import EVENT_COLLAB_SYNCED
from .account_events_service import (
CATEGORY_OPS,
EVENT_COLLAB_SYNCED,
EVENT_LEASE_ACQUIRED,
emit,
)
from .audit_service import record_account_action, record_audit
from .business_events import record_account_query
from .collab_common import apply_order_visibility, count_archived
@@ -59,6 +65,11 @@ from .douyu_goods_service import (
upsert_goods_snapshot,
)
from .file_service import build_file_url
from .platform_fulfillment.account_selector import (
acquire_account_lease,
active_lease_for_account,
release_lease,
)
# ---------------------------------------------------------------------------
# 状态机
@@ -72,6 +83,15 @@ STATUS_DONE = "done"
STATUS_POINTS_ERROR = "points_error"
STATUS_FAILED = "failed"
STATUS_VOID = "void"
LEASE_PURPOSE_DOUYU_COLLAB = "douyu_collab"
COLLAB_LEASE_STATUSES: tuple[str, ...] = (
STATUS_INCOMPLETE,
STATUS_TO_RECHARGE,
STATUS_RECHARGED,
STATUS_SCRIPTED,
STATUS_POINTS_ERROR,
STATUS_FAILED,
)
ORDER_STATUSES: tuple[str, ...] = (
STATUS_INCOMPLETE,
@@ -449,6 +469,308 @@ def _assert_mutable(order: DouyuExternalOrder) -> None:
raise CollabError("已作废的订单不能再编辑", code="order_void")
def _order_occupies_account(order: DouyuExternalOrder) -> bool:
return (
bool(order.account_id)
and order.archived_at is None
and order.status in COLLAB_LEASE_STATUSES
)
def _active_collab_order(
db: Session,
account_id: int,
*,
exclude_order_id: int | None = None,
) -> DouyuExternalOrder | None:
query = db.query(DouyuExternalOrder).filter(
DouyuExternalOrder.account_id == int(account_id),
DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES),
DouyuExternalOrder.archived_at.is_(None),
)
if exclude_order_id is not None:
query = query.filter(DouyuExternalOrder.id != int(exclude_order_id))
return query.order_by(DouyuExternalOrder.updated_at.desc()).first()
def _platform_lease_matches_source(
db: Session, lease: AccountLease, order: DouyuExternalOrder
) -> bool:
if (
lease.purpose != "platform_fulfillment"
or order.source_type != SOURCE_TYPE_PLATFORM_FULFILLMENT
or not order.source_task_id
):
return False
task = (
db.query(PlatformFulfillmentTask)
.filter(PlatformFulfillmentTask.id == int(order.source_task_id))
.first()
)
return bool(
task is not None
and (task.lease_id == lease.id or lease.batch_id == f"pf:{int(task.id)}")
)
def _audit_lease_action(
db: Session,
current: User,
*,
order: DouyuExternalOrder | None,
account_id: int,
action: str,
lease: AccountLease,
detail: Mapping[str, Any],
) -> None:
entry = record_audit(
db,
current,
action=action,
target=(
(
f"douyu_external_order:{order.id}"
if order.id
else f"douyu_external_order_no:{order.order_no}"
)
if order is not None
else f"account:{account_id}"
),
detail=detail,
)
entry.account_id = account_id
def _ensure_order_account_lease(
db: Session,
current: User,
order: DouyuExternalOrder,
*,
account_id: int | None = None,
force_active: bool = False,
commit: bool = False,
) -> AccountLease | None:
target_account_id = int(account_id or order.account_id or 0)
if not target_account_id:
return None
if not force_active and not _order_occupies_account(order):
return None
lease = active_lease_for_account(db, target_account_id)
if lease is not None:
if lease.purpose == LEASE_PURPOSE_DOUYU_COLLAB:
return lease
if _platform_lease_matches_source(db, lease, order):
return lease
raise CollabError(
"该账号当前被平台履约占用,请先释放或转人工后再使用",
status_code=409,
code="account_lease_conflict",
)
lease = acquire_account_lease(
db,
account_id=target_account_id,
holder_user_id=int(current.id),
scope="elite",
purpose=LEASE_PURPOSE_DOUYU_COLLAB,
batch_id=f"collab:{target_account_id}",
commit=False,
)
if lease is None:
raise CollabError(
"该账号刚被其他业务占用,请刷新后重试",
status_code=409,
code="account_lease_conflict",
)
_audit_lease_action(
db,
current,
order=order,
account_id=target_account_id,
action="douyu:collab:lease_acquired",
lease=lease,
detail={
"lease_id": lease.id,
"account_id": target_account_id,
"purpose": lease.purpose,
"batch_id": lease.batch_id,
},
)
if commit:
db.commit()
return lease
def _release_order_account_lease(
db: Session,
current: User,
order: DouyuExternalOrder,
*,
reason: str,
account_id: int | None = None,
commit: bool = False,
) -> bool:
target_account_id = int(account_id or order.account_id or 0)
if not target_account_id:
return False
if _active_collab_order(db, target_account_id, exclude_order_id=int(order.id)):
return False
lease = active_lease_for_account(db, target_account_id)
if lease is None or lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB:
return False
released = release_lease(db, lease, reason=reason, commit=False)
if released:
_audit_lease_action(
db,
current,
order=order,
account_id=target_account_id,
action="douyu:collab:lease_released",
lease=lease,
detail={
"lease_id": lease.id,
"account_id": target_account_id,
"reason": reason,
},
)
if commit:
db.commit()
return released
def _sync_order_lease(
db: Session,
current: User,
order: DouyuExternalOrder,
*,
reason: str,
force_active: bool = False,
commit: bool = False,
) -> AccountLease | None:
if force_active or _order_occupies_account(order):
return _ensure_order_account_lease(
db,
current,
order,
force_active=force_active,
commit=commit,
)
_release_order_account_lease(
db,
current,
order,
reason=reason,
commit=commit,
)
return None
def retain_lease_for_active_collab(
db: Session,
*,
account_id: int,
holder_user_id: int,
current: User | None = None,
lease: AccountLease | None = None,
source_task_id: int | None = None,
reason: str = "platform_release_to_collab",
commit: bool = False,
) -> AccountLease | None:
"""平台释放账号时,把仍在活动的协作占用接续为统一协作租约。"""
active_lease = lease or active_lease_for_account(db, account_id)
if active_lease is not None and active_lease.status != "active":
return None
query = db.query(DouyuExternalOrder).filter(
DouyuExternalOrder.account_id == int(account_id),
DouyuExternalOrder.status.in_(COLLAB_LEASE_STATUSES),
DouyuExternalOrder.archived_at.is_(None),
)
if source_task_id:
preferred = (
query.filter(DouyuExternalOrder.source_task_id == int(source_task_id))
.order_by(DouyuExternalOrder.updated_at.desc())
.first()
)
order = (
preferred or query.order_by(DouyuExternalOrder.updated_at.desc()).first()
)
else:
order = query.order_by(DouyuExternalOrder.updated_at.desc()).first()
if order is None:
return None
holder_id = int(
holder_user_id
or (order.owner_id if order.owner_id else 0)
or (active_lease.holder_user_id if active_lease else 0)
)
if not holder_id:
return None
if active_lease is None:
active_lease = acquire_account_lease(
db,
account_id=int(account_id),
holder_user_id=holder_id,
scope="elite",
purpose=LEASE_PURPOSE_DOUYU_COLLAB,
batch_id=f"collab:{int(account_id)}",
commit=False,
)
if active_lease is None:
return None
elif active_lease.purpose != LEASE_PURPOSE_DOUYU_COLLAB:
previous_purpose = active_lease.purpose
active_lease.purpose = LEASE_PURPOSE_DOUYU_COLLAB
active_lease.batch_id = f"collab:{int(account_id)}"[:64]
active_lease.commodity_id = ""
active_lease.expires_at = None
active_lease.release_reason = ""
active_lease.holder_user_id = holder_id
emit(
db,
account_id=int(account_id),
event_type=EVENT_LEASE_ACQUIRED,
title=f"外部协作接管账号占用:{order.order_no}",
category=CATEGORY_OPS,
detail={
"lease_id": active_lease.id,
"order_id": order.id,
"order_no": order.order_no,
"purpose": active_lease.purpose,
"previous_purpose": previous_purpose,
"reason": reason,
},
source="lease",
subject_type="order",
subject_key=order.order_no,
actor_type="user" if current is not None else "system",
actor_id=int(current.id) if current is not None else None,
source_ref=f"account_lease_collab_takeover:{active_lease.id}",
)
if current is not None:
_audit_lease_action(
db,
current,
order=order,
account_id=int(account_id),
action="douyu:collab:lease_takeover",
lease=active_lease,
detail={
"lease_id": active_lease.id,
"order_id": order.id,
"order_no": order.order_no,
"reason": reason,
},
)
if commit:
db.commit()
return active_lease
def _resolve_gift(
db: Session, *, gift_name: str, commodity_id: str, required_points: Any
) -> tuple[str, str, int | None]:
@@ -649,6 +971,7 @@ def create_order(
if order.shop:
ensure_shops_registered(db, current, [order.shop])
_ensure_order_account_lease(db, current, order, force_active=True)
db.add(order)
db.flush()
record_audit(
@@ -740,7 +1063,9 @@ def _apply_platform_fulfillment_binding(
if task.bind_task_id
else None
)
result = bind_task.result if bind_task and isinstance(bind_task.result, dict) else None
result = (
bind_task.result if bind_task and isinstance(bind_task.result, dict) else None
)
role = binding_role_from_result(result)
if not role:
return
@@ -875,6 +1200,12 @@ def sync_platform_fulfillment_order(
_apply_platform_fulfillment_status(order, task, created=created)
order.version = int(order.version or 0) + 1
db.flush()
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_sync_terminal",
)
audit_detail = {
"taskId": int(task.id),
@@ -982,9 +1313,7 @@ def sync_platform_fulfillment_orders(
}
)
except Exception: # noqa: BLE001 - 批量边界需隔离单条未知故障
logger.exception(
"同步直播履约任务 {} 到斗鱼外部协作失败", task_id
)
logger.exception("同步直播履约任务 {} 到斗鱼外部协作失败", task_id)
result["failed"] += 1
result["items"].append(
{
@@ -1013,6 +1342,7 @@ def update_order(
) -> dict[str, Any]:
_assert_mutable(order)
_assert_version(order, expected_version)
previous_account_id = int(order.account_id or 0)
changes: dict[str, dict[str, Any]] = {}
editable = {
"order_no",
@@ -1075,8 +1405,18 @@ def update_order(
client=client,
with_goods=True,
)
_ensure_order_account_lease(
db,
current,
order,
account_id=int(account.id),
force_active=order.status in COLLAB_LEASE_STATUSES,
)
apply_probe_snapshot(order, account, probe)
changes["account_id"] = {"old": None, "new": int(account.id)}
changes["account_id"] = {
"old": previous_account_id or None,
"new": int(account.id),
}
changes["bind_game_role"] = {"old": "", "new": order.bind_game_role}
if "home_images" in payload:
images = normalize_images(payload.get("home_images"))
@@ -1107,6 +1447,14 @@ def update_order(
detail=changes,
)
_maybe_advance_to_recharge(db, current, order)
if previous_account_id and previous_account_id != int(order.account_id or 0):
_release_order_account_lease(
db,
current,
order,
reason="douyu_collab_account_changed",
account_id=previous_account_id,
)
if commit:
db.commit()
db.refresh(order)
@@ -1128,6 +1476,7 @@ def set_account(
account = account_by_username(db, username)
if account is None:
raise CollabError("斗鱼账号不存在", code="account_not_found")
previous_account_id = int(order.account_id or 0)
config = resolve_config(db)
probe = _probe_with_client(
account,
@@ -1137,6 +1486,13 @@ def set_account(
client=client,
with_goods=True,
)
_ensure_order_account_lease(
db,
current,
order,
account_id=int(account.id),
force_active=order.status in COLLAB_LEASE_STATUSES,
)
apply_probe_snapshot(order, account, probe)
order.updated_by = current.id
order.version = int(order.version or 0) + 1
@@ -1153,6 +1509,14 @@ def set_account(
},
)
_maybe_advance_to_recharge(db, current, order)
if previous_account_id and previous_account_id != int(order.account_id or 0):
_release_order_account_lease(
db,
current,
order,
reason="douyu_collab_account_changed",
account_id=previous_account_id,
)
if commit:
db.commit()
db.refresh(order)
@@ -1249,6 +1613,8 @@ def _restore_void_status(
target_index = STAGE_INDEX.get(target)
if target_index is not None and target_index >= STAGE_INDEX[STATUS_TO_RECHARGE]:
_assert_ready_for_recharge(order)
if target in COLLAB_LEASE_STATUSES:
_ensure_order_account_lease(db, current, order, force_active=True)
old_void_reason = order.void_reason or ""
# 取消作废等于重新进入状态机:先清空旧流程时间,再按目标状态补当前时间。
@@ -1275,6 +1641,12 @@ def _restore_void_status(
"reason": _text(reason, max_length=256),
},
)
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_void_restored",
)
if commit:
db.commit()
db.refresh(order)
@@ -1324,6 +1696,12 @@ def set_status(
target=_status_audit_target(order),
detail={"from": old, "reason": order.void_reason},
)
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_void",
)
if commit:
db.commit()
db.refresh(order)
@@ -1340,6 +1718,12 @@ def set_status(
target=_status_audit_target(order),
detail={"from": old, "to": target, "reason": _text(reason, max_length=256)},
)
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_failed",
)
if commit:
db.commit()
db.refresh(order)
@@ -1356,6 +1740,12 @@ def set_status(
target=_status_audit_target(order),
detail={"from": old, "reason": _text(reason, max_length=256)},
)
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_points_error",
)
if commit:
db.commit()
db.refresh(order)
@@ -1399,6 +1789,16 @@ def set_status(
"reason": _text(reason, max_length=256),
},
)
_sync_order_lease(
db,
current,
order,
reason=(
"douyu_collab_done"
if target == STATUS_DONE
else "douyu_collab_status_changed"
),
)
if commit:
db.commit()
db.refresh(order)
@@ -2508,6 +2908,12 @@ def archive_orders(
target=_status_audit_target(order),
detail={"reason": order.archive_reason},
)
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_archived",
)
db.commit()
return {"archived": archived}
@@ -2536,6 +2942,12 @@ def unarchive_orders(db: Session, current: User, ids: list[int]) -> dict[str, An
target=_status_audit_target(order),
detail={},
)
_sync_order_lease(
db,
current,
order,
reason="douyu_collab_unarchived",
)
db.commit()
return {"unarchived": unarchived}
@@ -2544,6 +2956,12 @@ def delete_order(
db: Session, current: User, order: DouyuExternalOrder
) -> dict[str, Any]:
order_no = order.order_no
_release_order_account_lease(
db,
current,
order,
reason="douyu_collab_deleted",
)
record_audit(
db,
current,