fix(platform): 防止绑定任务压垮连接池和事件循环

This commit is contained in:
yml
2026-11-21 15:22:46 +08:00
parent d199e04d27
commit e1d979a296
13 changed files with 336 additions and 46 deletions
@@ -2,9 +2,9 @@
from __future__ import annotations
import asyncio
import os
import threading
import time
from collections.abc import Iterable
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -18,6 +18,7 @@ from ...models import PlatformFulfillmentTask
from . import service
DEFAULT_INTERVAL_SECONDS = 20
DEFAULT_MIN_INTERVAL_SECONDS = 5
DEFAULT_BATCH_SIZE = 2
DEFAULT_RETRY_SECONDS = 45
@@ -144,12 +145,10 @@ def run_auto_allocation_once(
allocated_task.next_allocate_at = None
db.commit()
try:
asyncio.run(
service.start_binding(
db,
task_id=candidate_task_id,
current=actor,
)
service.start_binding_sync(
db,
task_id=candidate_task_id,
current=actor,
)
except Exception as exc: # noqa: BLE001 - allocation remains valid
db.rollback()
@@ -211,12 +210,10 @@ def start_allocated_bindings_once(
started = 0
for task in rows:
try:
asyncio.run(
service.start_binding(
db,
task_id=int(task.id),
current=actor,
)
service.start_binding_sync(
db,
task_id=int(task.id),
current=actor,
)
started += 1
except Exception as exc: # noqa: BLE001 - one session cannot block the rest
@@ -237,6 +234,7 @@ def _run() -> None:
3600,
)
while not _stop_event.is_set():
tick_started = time.monotonic()
db = WorkerSessionLocal()
try:
pending_ids = _take_pending_task_ids(
@@ -260,6 +258,15 @@ def _run() -> None:
db.close()
if _stop_event.is_set():
break
min_interval = _env_int(
"PLATFORM_FULFILLMENT_AUTO_ALLOCATE_MIN_INTERVAL_SECONDS",
DEFAULT_MIN_INTERVAL_SECONDS,
1,
60,
)
remaining = min_interval - (time.monotonic() - tick_started)
if remaining > 0 and _stop_event.wait(remaining):
break
if _has_pending_task_ids():
continue
_wake_event.wait(interval)
@@ -14,6 +14,7 @@ from loguru import logger
from sqlalchemy import func, or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from starlette.concurrency import run_in_threadpool
from ...models import (
Account,
@@ -2433,7 +2434,7 @@ def reset_task_binding(
return get_task_detail(db, task.id)
async def start_binding(
def start_binding_sync(
db: Session,
*,
task_id: int,
@@ -2536,6 +2537,23 @@ async def start_binding(
return get_task_detail(db, task.id)
async def start_binding(
db: Session,
*,
task_id: int,
current: User,
force_refresh: bool = False,
) -> dict[str, Any]:
"""Run the blocking DB/network dispatch path outside the ASGI event loop."""
return await run_in_threadpool(
start_binding_sync,
db,
task_id=task_id,
current=current,
force_refresh=force_refresh,
)
def refresh_binding(db: Session, *, task_id: int) -> dict[str, Any]:
task = _load_task(db, task_id)
if task.execution_status in {"completed", "cancelled"}:
@@ -2677,7 +2695,7 @@ def reconcile_binding_state_outbox(
}
async def confirm_binding(
def confirm_binding_sync(
db: Session, *, task_id: int, current: User
) -> dict[str, Any]:
task = _load_task_for_update(db, task_id)
@@ -2754,6 +2772,17 @@ async def confirm_binding(
return get_task_detail(db, task.id)
async def confirm_binding(
db: Session, *, task_id: int, current: User
) -> dict[str, Any]:
return await run_in_threadpool(
confirm_binding_sync,
db,
task_id=task_id,
current=current,
)
def refresh_exchange_eligibility(
db: Session, *, task_id: int, current: User
) -> dict[str, Any]: