fix(douyu): 统一外部协作账号租约
This commit is contained in:
@@ -290,14 +290,45 @@ def lease_account(
|
||||
now: datetime | None = None,
|
||||
) -> AccountLease | None:
|
||||
"""尝试领取一个账号;撞唯一索引时返回 None。"""
|
||||
moment = _now(now)
|
||||
lease = AccountLease(
|
||||
account_id=candidate.account_id,
|
||||
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=(
|
||||
@@ -316,30 +347,54 @@ def lease_account(
|
||||
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(candidate.account_id),
|
||||
account_id=int(account_id),
|
||||
event_type=EVENT_LEASE_ACQUIRED,
|
||||
title=f"履约占用:任务 #{task_id}",
|
||||
title=(
|
||||
f"履约占用:任务 #{batch_id.removeprefix('pf:')}"
|
||||
if purpose == "platform_fulfillment"
|
||||
else f"业务占用:{purpose}"
|
||||
),
|
||||
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",
|
||||
},
|
||||
occurred_at=moment,
|
||||
detail=event_detail,
|
||||
source="lease",
|
||||
subject_type="task",
|
||||
subject_key=str(task_id),
|
||||
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}",
|
||||
)
|
||||
db.commit()
|
||||
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,
|
||||
@@ -364,6 +419,7 @@ def release_lease(
|
||||
*,
|
||||
reason: str,
|
||||
now: datetime | None = None,
|
||||
commit: bool = True,
|
||||
) -> bool:
|
||||
if lease is None or lease.status != "active":
|
||||
return False
|
||||
@@ -387,7 +443,8 @@ def release_lease(
|
||||
actor_type="system",
|
||||
source_ref=f"account_lease_released:{lease.id}",
|
||||
)
|
||||
db.commit()
|
||||
if commit:
|
||||
db.commit()
|
||||
return True
|
||||
|
||||
|
||||
@@ -442,6 +499,8 @@ __all__ = [
|
||||
"EXCHANGE_COOLDOWN_DAYS",
|
||||
"VALIDATION_LEASE_MINUTES",
|
||||
"AccountCandidate",
|
||||
"acquire_account_lease",
|
||||
"active_lease_for_account",
|
||||
"capability_candidate_accounts",
|
||||
"eligible_accounts",
|
||||
"expire_platform_fulfillment_leases",
|
||||
|
||||
@@ -82,6 +82,7 @@ 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")
|
||||
@@ -150,7 +151,9 @@ def _upsert_order_snapshot(
|
||||
) -> tuple[PlatformFulfillmentTask | None, bool, bool]:
|
||||
"""应用一条订单项快照,返回 (task, created, ignored)。"""
|
||||
item_id = str(
|
||||
_snapshot_value(snapshot, "sourceOrderItemId", "source_order_item_id", default="")
|
||||
_snapshot_value(
|
||||
snapshot, "sourceOrderItemId", "source_order_item_id", default=""
|
||||
)
|
||||
).strip()
|
||||
if not item_id:
|
||||
return None, False, True
|
||||
@@ -177,11 +180,7 @@ def _upsert_order_snapshot(
|
||||
return None, False, True
|
||||
cutoff = _order_match_started_at(db)
|
||||
match_basis_at = paid_at or order_created_at
|
||||
if (
|
||||
match_basis_at is not None
|
||||
and cutoff is not None
|
||||
and match_basis_at < cutoff
|
||||
):
|
||||
if match_basis_at is not None and cutoff is not None and match_basis_at < cutoff:
|
||||
return None, False, True
|
||||
|
||||
task = (
|
||||
@@ -303,21 +302,11 @@ def _upsert_order_snapshot(
|
||||
default=task.source_fulfillment_id,
|
||||
)
|
||||
)
|
||||
task.provider = str(
|
||||
_snapshot_value(snapshot, "provider", default=task.provider)
|
||||
)
|
||||
task.shop_id = str(
|
||||
_snapshot_value(snapshot, "shopId", "shop_id", default="")
|
||||
)
|
||||
task.shop_name = str(
|
||||
_snapshot_value(snapshot, "shopName", "shop_name", default="")
|
||||
)
|
||||
task.sku_code = str(
|
||||
_snapshot_value(snapshot, "skuCode", "sku_code", default="")
|
||||
)
|
||||
task.sku_name = str(
|
||||
_snapshot_value(snapshot, "skuName", "sku_name", default="")
|
||||
)
|
||||
task.provider = str(_snapshot_value(snapshot, "provider", default=task.provider))
|
||||
task.shop_id = str(_snapshot_value(snapshot, "shopId", "shop_id", default=""))
|
||||
task.shop_name = str(_snapshot_value(snapshot, "shopName", "shop_name", default=""))
|
||||
task.sku_code = str(_snapshot_value(snapshot, "skuCode", "sku_code", default=""))
|
||||
task.sku_name = str(_snapshot_value(snapshot, "skuName", "sku_name", default=""))
|
||||
task.internal_sku_key = str(
|
||||
_snapshot_value(
|
||||
snapshot,
|
||||
@@ -453,7 +442,9 @@ def sync_order_item_ids(
|
||||
updated = 0
|
||||
ignored = 0
|
||||
task_ids: list[int] = []
|
||||
for item_id in dict.fromkeys(str(item or "").strip() for item in source_order_item_ids):
|
||||
for item_id in dict.fromkeys(
|
||||
str(item or "").strip() for item in source_order_item_ids
|
||||
):
|
||||
if not item_id:
|
||||
ignored += 1
|
||||
continue
|
||||
@@ -461,7 +452,9 @@ def sync_order_item_ids(
|
||||
if snapshot is None:
|
||||
ignored += 1
|
||||
continue
|
||||
mapping = mapping_by_sku.get(str(snapshot.get("internal_sku_key") or "").strip())
|
||||
mapping = mapping_by_sku.get(
|
||||
str(snapshot.get("internal_sku_key") or "").strip()
|
||||
)
|
||||
task, was_created, was_ignored = _upsert_order_snapshot(
|
||||
db,
|
||||
snapshot,
|
||||
@@ -765,6 +758,31 @@ def _load_task(db: Session, task_id: int) -> PlatformFulfillmentTask:
|
||||
return task
|
||||
|
||||
|
||||
def _retain_lease_for_active_collab(
|
||||
db: Session,
|
||||
*,
|
||||
task: PlatformFulfillmentTask,
|
||||
lease: AccountLease | None,
|
||||
current: User,
|
||||
reason: str,
|
||||
) -> AccountLease | None:
|
||||
"""平台释放账号前,把仍在活动的协作单占用接续到同一租约。"""
|
||||
if lease is None or not task.account_id:
|
||||
return None
|
||||
from ..douyu_collab_service import retain_lease_for_active_collab
|
||||
|
||||
return retain_lease_for_active_collab(
|
||||
db,
|
||||
account_id=int(task.account_id),
|
||||
holder_user_id=int(current.id),
|
||||
current=current,
|
||||
lease=lease,
|
||||
source_task_id=int(task.id),
|
||||
reason=reason,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
|
||||
def _apply_mapping(
|
||||
task: PlatformFulfillmentTask,
|
||||
mapping: PlatformCommodityMapping | None,
|
||||
@@ -892,10 +910,10 @@ def _sync_pending_tasks(
|
||||
task.scope = SCOPE_ELITE
|
||||
task.source_snapshot_json = _jsonable(row)
|
||||
task.updated_at = _now()
|
||||
if (
|
||||
task.account_id is None
|
||||
and 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()
|
||||
@@ -1135,13 +1153,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
||||
actor_ids = {
|
||||
int(event.actor_id)
|
||||
for event in events
|
||||
if event.actor_type == "user"
|
||||
and str(event.actor_id or "").isdigit()
|
||||
if event.actor_type == "user" and str(event.actor_id or "").isdigit()
|
||||
}
|
||||
actors = {
|
||||
int(user.id): user
|
||||
for user in db.query(User).filter(User.id.in_(actor_ids)).all()
|
||||
} if actor_ids else {}
|
||||
actors = (
|
||||
{
|
||||
int(user.id): user
|
||||
for user in db.query(User).filter(User.id.in_(actor_ids)).all()
|
||||
}
|
||||
if actor_ids
|
||||
else {}
|
||||
)
|
||||
return {
|
||||
"task": _task_out(db, task, include_qr=True),
|
||||
"events": [
|
||||
@@ -1154,19 +1175,16 @@ def get_task_detail(db: Session, task_id: int) -> dict[str, Any]:
|
||||
actors[int(event.actor_id)].deleted_username
|
||||
or actors[int(event.actor_id)].username
|
||||
)
|
||||
if str(event.actor_id or "").isdigit()
|
||||
and int(event.actor_id) in actors
|
||||
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
|
||||
else "",
|
||||
"actorRole": actors[int(event.actor_id)].role
|
||||
if str(event.actor_id or "").isdigit()
|
||||
and int(event.actor_id) in actors
|
||||
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
|
||||
else "",
|
||||
"actorRoleLabel": ROLE_LABELS.get(
|
||||
actors[int(event.actor_id)].role,
|
||||
actors[int(event.actor_id)].role,
|
||||
)
|
||||
if str(event.actor_id or "").isdigit()
|
||||
and int(event.actor_id) in actors
|
||||
if str(event.actor_id or "").isdigit() and int(event.actor_id) in actors
|
||||
else "",
|
||||
"detail": event.detail_json or {},
|
||||
"createdAt": event.created_at,
|
||||
@@ -1542,9 +1560,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
|
||||
availability=(
|
||||
AVAILABILITY_LIMITED if limited else AVAILABILITY_AVAILABLE
|
||||
),
|
||||
blocking_reason=(
|
||||
"该账号已达此商品兑换上限" if limited else ""
|
||||
),
|
||||
blocking_reason=("该账号已达此商品兑换上限" if limited else ""),
|
||||
raw_status="1" if limited else "0",
|
||||
observed_at=live_state.checked_at,
|
||||
source="live_check",
|
||||
@@ -1742,7 +1758,15 @@ def release_task_account(
|
||||
if task.lease_id
|
||||
else None
|
||||
)
|
||||
release_lease(db, lease, reason=reason)
|
||||
retained = _retain_lease_for_active_collab(
|
||||
db,
|
||||
task=task,
|
||||
lease=lease,
|
||||
current=current,
|
||||
reason="platform_released_to_collab",
|
||||
)
|
||||
if retained is None:
|
||||
release_lease(db, lease, reason=reason, commit=False)
|
||||
task.account_id = None
|
||||
task.lease_id = None
|
||||
task.bind_task_id = None
|
||||
@@ -2057,7 +2081,7 @@ def reconcile_binding_state_outbox(
|
||||
PlatformFulfillmentTask.id > normalized_after,
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
["completed", "cancelled"]
|
||||
)
|
||||
),
|
||||
)
|
||||
.order_by(PlatformFulfillmentTask.id.asc())
|
||||
.limit(batch_size)
|
||||
@@ -2297,7 +2321,20 @@ def complete_manual_exchange(
|
||||
task.last_error = ""
|
||||
task.issue_code = ""
|
||||
task.updated_at = _now()
|
||||
release_lease(db, lease, reason="manual_exchange_completed")
|
||||
retained = _retain_lease_for_active_collab(
|
||||
db,
|
||||
task=task,
|
||||
lease=lease,
|
||||
current=current,
|
||||
reason="platform_completed_but_collab_active",
|
||||
)
|
||||
if retained is None:
|
||||
release_lease(
|
||||
db,
|
||||
lease,
|
||||
reason="manual_exchange_completed",
|
||||
commit=False,
|
||||
)
|
||||
_append_event(
|
||||
db,
|
||||
task.id,
|
||||
@@ -2378,7 +2415,20 @@ def cancel_task(
|
||||
linked_task.status = "stopped"
|
||||
linked_task.message = "履约任务已取消"
|
||||
linked_task.finished_at = _now()
|
||||
release_lease(db, lease, reason="platform_fulfillment_cancelled")
|
||||
retained = _retain_lease_for_active_collab(
|
||||
db,
|
||||
task=task,
|
||||
lease=lease,
|
||||
current=current,
|
||||
reason="platform_cancelled_but_collab_active",
|
||||
)
|
||||
if retained is None:
|
||||
release_lease(
|
||||
db,
|
||||
lease,
|
||||
reason="platform_fulfillment_cancelled",
|
||||
commit=False,
|
||||
)
|
||||
task.account_id = None
|
||||
task.lease_id = None
|
||||
task.bind_task_id = None
|
||||
@@ -2455,7 +2505,9 @@ def restore_cancelled_task(
|
||||
or str(source.get("fulfillment_issue_code") or "")
|
||||
in {"user_refund", "platform_cancelled"}
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="来源订单已退款、关闭或取消,不能恢复")
|
||||
raise HTTPException(
|
||||
status_code=409, detail="来源订单已退款、关闭或取消,不能恢复"
|
||||
)
|
||||
|
||||
restore_reason = reason.strip()
|
||||
if len(restore_reason) < 2:
|
||||
@@ -2537,7 +2589,20 @@ def release_task_to_manual(
|
||||
if task.lease_id
|
||||
else None
|
||||
)
|
||||
release_lease(db, lease, reason="platform_fulfillment_manual")
|
||||
retained = _retain_lease_for_active_collab(
|
||||
db,
|
||||
task=task,
|
||||
lease=lease,
|
||||
current=current,
|
||||
reason="platform_release_to_manual",
|
||||
)
|
||||
if retained is None:
|
||||
release_lease(
|
||||
db,
|
||||
lease,
|
||||
reason="platform_fulfillment_manual",
|
||||
commit=False,
|
||||
)
|
||||
task.account_id = None
|
||||
task.lease_id = None
|
||||
task.bind_task_id = None
|
||||
|
||||
Reference in New Issue
Block a user