diff --git a/tests/test_platform_fulfillment_auto_allocator.py b/tests/test_platform_fulfillment_auto_allocator.py index 6574884..6ab110d 100644 --- a/tests/test_platform_fulfillment_auto_allocator.py +++ b/tests/test_platform_fulfillment_auto_allocator.py @@ -104,6 +104,70 @@ def test_auto_allocator_only_scans_ready_unassigned_tasks(db): assert not auto_allocator._running_task_ids +def test_auto_allocator_skips_task_already_claimed_by_another_caller(db): + actor = User(username="auto-running-actor", password_hash="h", role="super_admin") + db.add( + PlatformFulfillmentSetting( + id=1, + lease_duration_minutes=None, + order_match_started_at=datetime.now(UTC) - timedelta(days=1), + ) + ) + task = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="running-1", + source_order_item_id="running-1", + platform_order_id="AUTO-RUNNING", + internal_sku_key="skin", + commodity_id="commodity-1", + execution_status="ready", + binding_status="not_started", + exchange_status="not_started", + paid_at=datetime.now(UTC), + next_allocate_at=datetime.now(UTC), + updated_at=datetime.now(UTC), + ) + db.add_all([actor, task]) + db.commit() + auto_allocator._running_task_ids.add(task.id) + try: + with patch.object( + auto_allocator.service, + "allocate_task", + side_effect=AssertionError("running task must not be allocated twice"), + ): + result = auto_allocator.run_auto_allocation_once(db, limit=1) + finally: + auto_allocator._running_task_ids.discard(task.id) + + assert result == {"checked": 0, "allocated": 0, "failed": 0} + + +def test_immediate_allocation_runs_and_wakes_background_retry(db): + expected = {"checked": 1, "allocated": 1, "failed": 0} + session = object() + with ( + patch.object( + auto_allocator, + "run_auto_allocation_once", + return_value=expected, + ) as run, + patch.object(auto_allocator, "wake_auto_allocator") as wake, + ): + result = auto_allocator.run_immediate_allocation( + session, + task_ids=[9, 9, 10], + ) + + assert result == expected + run.assert_called_once_with( + session, + limit=2, + task_ids=[9, 10], + ) + wake.assert_called_once_with([9, 10]) + + def test_auto_allocator_schedules_retry_only_after_failed_allocation(db): actor = User(username="auto-retry-actor", password_hash="h", role="super_admin") db.add( diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index 0003dc4..704f369 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -99,10 +99,14 @@ def sync_tasks( current: User = Depends(require_permission("platform_fulfillment:use")), ) -> dict[str, Any]: result = service.sync_pending_tasks(db, limit=limit) - if result.get("taskIds"): - from ..services.platform_fulfillment.auto_allocator import wake_auto_allocator + from ..services.platform_fulfillment.auto_allocator import ( + run_immediate_allocation, + ) - wake_auto_allocator(result["taskIds"]) + result["immediateAllocation"] = run_immediate_allocation( + db, + task_ids=result.get("taskIds", []), + ) record_audit( db, current, diff --git a/web/backend/routers/platform_fulfillment_integration.py b/web/backend/routers/platform_fulfillment_integration.py index 01df94d..513d47a 100644 --- a/web/backend/routers/platform_fulfillment_integration.py +++ b/web/backend/routers/platform_fulfillment_integration.py @@ -107,8 +107,15 @@ async def sync_order_event( result = service.sync_order_item_ids(db, item_ids, commit=False) inbox.processed_at = datetime.now(UTC) db.commit() - auto_allocator.wake_auto_allocator(result.get("taskIds", [])) - return {**result, "duplicate": False} + task_ids = [ + int(task_id) for task_id in result.get("taskIds", []) if str(task_id).isdigit() + ] + immediate = auto_allocator.run_immediate_allocation(db, task_ids=task_ids) + return { + **result, + "duplicate": False, + "immediateAllocation": immediate, + } @router.post( diff --git a/web/backend/services/platform_fulfillment/auto_allocator.py b/web/backend/services/platform_fulfillment/auto_allocator.py index fe809ca..48564ad 100644 --- a/web/backend/services/platform_fulfillment/auto_allocator.py +++ b/web/backend/services/platform_fulfillment/auto_allocator.py @@ -78,9 +78,12 @@ def _take_pending_task_ids(limit: int) -> list[int]: def _claim_running_task_ids(task_ids: Iterable[int]) -> list[int]: normalized = [int(task_id) for task_id in task_ids] with _pending_lock: - _running_task_ids.update(normalized) - _pending_task_ids.difference_update(normalized) - return normalized + claimed = [ + task_id for task_id in normalized if task_id not in _running_task_ids + ] + _running_task_ids.update(claimed) + _pending_task_ids.difference_update(claimed) + return claimed def _release_running_task_ids(task_ids: Iterable[int]) -> None: @@ -165,9 +168,11 @@ def run_auto_allocation_once( if not candidates: return {"checked": 0, "allocated": 0, "failed": 0} - candidate_task_ids = _claim_running_task_ids( - int(task.id) for task in candidates - ) + candidate_task_ids = _claim_running_task_ids(int(task.id) for task in candidates) + if not candidate_task_ids: + return {"checked": 0, "allocated": 0, "failed": 0} + claimed_task_ids = set(candidate_task_ids) + candidates = [task for task in candidates if int(task.id) in claimed_task_ids] try: actor = service._integration_actor(db) allocated = 0 @@ -230,6 +235,35 @@ def run_auto_allocation_once( _release_running_task_ids(candidate_task_ids) +def run_immediate_allocation( + db: Session, + *, + task_ids: Iterable[int], +) -> dict[str, int]: + """Webhook 已同步新订单后立即尝试选号,避免等待低优先级后台线程。""" + normalized_ids = [ + int(task_id) for task_id in dict.fromkeys(task_ids or []) if int(task_id) > 0 + ] + if not normalized_ids: + return {"checked": 0, "allocated": 0, "failed": 0} + try: + return run_auto_allocation_once( + db, + limit=min(len(normalized_ids), DEFAULT_BATCH_SIZE), + task_ids=normalized_ids, + ) + except Exception as exc: # noqa: BLE001 - webhook sync remains committed + db.rollback() + logger.warning("直播账号履约即时选号失败: {}", exc) + return { + "checked": len(normalized_ids), + "allocated": 0, + "failed": len(normalized_ids), + } + finally: + wake_auto_allocator(normalized_ids) + + def start_allocated_bindings_once( db: Session, *, @@ -244,7 +278,9 @@ def start_allocated_bindings_once( PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.lease_id.isnot(None), ) - .order_by(PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc()) + .order_by( + PlatformFulfillmentTask.updated_at.asc(), PlatformFulfillmentTask.id.asc() + ) .limit(max(1, limit)) .all() )