feat(fulfillment): 增加工作台状态事件同步

This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent 3a8f12ae43
commit 00c4a268c2
10 changed files with 262 additions and 10 deletions
@@ -3,8 +3,10 @@
from __future__ import annotations
import os
import time
import uuid
from datetime import UTC, datetime, timedelta
from threading import Lock
from typing import Any
from fastapi import HTTPException
@@ -38,6 +40,7 @@ from .account_selector import (
release_lease,
renew_lease,
)
from .order_site_notifier import notify_order_site_binding_state_async
TARGET_PLATFORM = "douyu"
SCOPE_ELITE = "elite"
@@ -52,6 +55,11 @@ ACTIVE_STATUSES = {
}
BINDING_QR_TTL_SECONDS = int(os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "600"))
AUTO_SYNC_INTERVAL_SECONDS = 60.0
_SYNC_LOCK = Lock()
_AUTO_SYNC_LOCK = Lock()
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
def _now() -> datetime:
@@ -251,7 +259,7 @@ def _apply_mapping(
task.last_error = ""
def sync_pending_tasks(db: Session, *, limit: int = 100) -> dict[str, Any]:
def _sync_pending_tasks(db: Session, *, limit: int = 100) -> dict[str, Any]:
"""从 order_site 拉取人工待履约订单项并幂等生成本地作业。"""
try:
rows = list_pending_manual_fulfillments(limit=limit)
@@ -317,6 +325,37 @@ def sync_pending_tasks(db: Session, *, limit: int = 100) -> dict[str, Any]:
return {"fetched": len(rows), "created": created, "updated": updated}
def sync_pending_tasks(db: Session, *, limit: int = 100) -> dict[str, Any]:
"""串行同步订单,避免自动同步与人工同步并发创建重复任务。"""
with _SYNC_LOCK:
return _sync_pending_tasks(db, limit=limit)
def sync_pending_tasks_if_due(
db: Session,
*,
limit: int = 100,
now: float | None = None,
) -> dict[str, Any] | None:
"""工作台读取时自动同步;按进程节流,不阻塞每 5 秒一次的列表轮询。"""
global _AUTO_SYNC_LAST_ATTEMPT
if not _AUTO_SYNC_LOCK.acquire(blocking=False):
return None
try:
current = time.monotonic() if now is None else now
if current - _AUTO_SYNC_LAST_ATTEMPT < AUTO_SYNC_INTERVAL_SECONDS:
return None
_AUTO_SYNC_LAST_ATTEMPT = current
try:
return sync_pending_tasks(db, limit=limit)
except Exception:
_AUTO_SYNC_LAST_ATTEMPT = float("-inf")
raise
finally:
_AUTO_SYNC_LOCK.release()
def list_tasks(
db: Session,
*,
@@ -609,6 +648,21 @@ def customer_refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
return customer_binding_out(db, task_id)
def customer_refresh_bindings(db: Session, *, task_ids: list[int]) -> dict[str, Any]:
items: list[dict[str, Any]] = []
for task_id in dict.fromkeys(task_ids):
task = (
db.query(PlatformFulfillmentTask)
.filter(PlatformFulfillmentTask.id == task_id)
.first()
)
if task is None:
continue
refresh_binding(db, task_id=task.id)
items.append(customer_binding_out(db, task.id))
return {"items": items}
async def customer_confirm_binding(db: Session, *, task_id: int) -> dict[str, Any]:
refresh_binding(db, task_id=task_id)
await confirm_binding(db, task_id=task_id, current=_integration_actor(db))
@@ -839,6 +893,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
task.account_id = selected.account_id
@@ -882,6 +937,7 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
@@ -917,6 +973,7 @@ def release_task_account(
detail={"reason": reason},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
@@ -988,6 +1045,7 @@ async def start_binding(
detail={"bindTaskId": bind_task.id},
)
db.commit()
notify_order_site_binding_state_async(task.id)
start_douyu_batch(
batch_id=batch_id,
task_type="get_bind_qr",
@@ -1004,6 +1062,13 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
bind_task = db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
if bind_task is None:
return get_task_detail(db, task.id)
before = (
task.binding_status,
task.execution_status,
task.exchange_status,
task.issue_code,
task.last_error,
)
result = bind_task.result or {}
if bind_task.status in {"failed", "error", "stopped"}:
task.binding_status = "failed"
@@ -1027,6 +1092,15 @@ def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
task.last_error = ""
task.updated_at = _now()
db.commit()
after = (
task.binding_status,
task.execution_status,
task.exchange_status,
task.issue_code,
task.last_error,
)
if after != before:
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
@@ -1072,6 +1146,7 @@ async def confirm_binding(
detail={"confirmTaskId": confirm_task.id},
)
db.commit()
notify_order_site_binding_state_async(task.id)
start_douyu_batch(
batch_id=batch_id,
task_type="confirm_bind",
@@ -1118,6 +1193,7 @@ def refresh_exchange_eligibility(
detail={"error": str(exc)},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
if task.commodity_id in eligibility.limited_ids:
@@ -1153,6 +1229,7 @@ def refresh_exchange_eligibility(
},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
@@ -1193,6 +1270,7 @@ def complete_manual_exchange(
detail={"note": note[:1000]},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
@@ -1218,6 +1296,7 @@ def mark_manual_required(
detail={"reason": task.last_error},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
@@ -1248,6 +1327,7 @@ def cancel_task(
detail={"reason": task.last_error},
)
db.commit()
notify_order_site_binding_state_async(task.id)
return get_task_detail(db, task.id)
@@ -1256,6 +1336,7 @@ __all__ = [
"cancel_task",
"complete_manual_exchange",
"confirm_binding",
"customer_refresh_bindings",
"get_task_detail",
"list_mappings",
"list_tasks",
@@ -1265,5 +1346,6 @@ __all__ = [
"release_task_account",
"start_binding",
"sync_pending_tasks",
"sync_pending_tasks_if_due",
"upsert_mapping",
]