perf(automation): 持久队列驱动并优化履约热路径
This commit is contained in:
@@ -2,6 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import weakref
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
@@ -40,6 +44,159 @@ from .common import (
|
||||
)
|
||||
from .repository import _load_task
|
||||
|
||||
_TASK_COUNT_CACHE_TTL_SECONDS = 15.0
|
||||
_TASK_COUNT_CACHE_MAX_ENTRIES = 512
|
||||
_TASK_COUNT_CACHE: weakref.WeakKeyDictionary[
|
||||
Any, dict[tuple[Any, ...], tuple[float, int]]
|
||||
] = weakref.WeakKeyDictionary()
|
||||
_TASK_COUNT_CACHE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
@dataclass
|
||||
class _TaskOutputContext:
|
||||
mappings: dict[int, PlatformCommodityMapping]
|
||||
goods: dict[str, DouyuGoodsSnapshot]
|
||||
accounts: dict[int, Account]
|
||||
leases: dict[int, AccountLease]
|
||||
bind_tasks: dict[int, DouyuTask]
|
||||
collab_orders: dict[int, DouyuExternalOrder]
|
||||
|
||||
|
||||
def invalidate_task_list_count_cache() -> None:
|
||||
"""任务写入后清空分页总数缓存,最多 15 秒的跨进程陈旧由 TTL 兜底。"""
|
||||
with _TASK_COUNT_CACHE_LOCK:
|
||||
_TASK_COUNT_CACHE.clear()
|
||||
|
||||
|
||||
def _count_cache_key(
|
||||
*,
|
||||
cutoff: datetime | None,
|
||||
status: str,
|
||||
queue_bucket: str,
|
||||
sale_mode: str,
|
||||
keyword: str,
|
||||
) -> tuple[Any, ...]:
|
||||
return (
|
||||
cutoff,
|
||||
status,
|
||||
queue_bucket,
|
||||
sale_mode,
|
||||
keyword.strip(),
|
||||
)
|
||||
|
||||
|
||||
def _cached_task_count(
|
||||
db: Session,
|
||||
query,
|
||||
*,
|
||||
key: tuple[Any, ...],
|
||||
) -> int:
|
||||
moment = time.monotonic()
|
||||
bind = db.get_bind()
|
||||
with _TASK_COUNT_CACHE_LOCK:
|
||||
engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {})
|
||||
cached = engine_cache.get(key)
|
||||
if cached and moment - cached[0] < _TASK_COUNT_CACHE_TTL_SECONDS:
|
||||
return cached[1]
|
||||
total = int(query.count())
|
||||
with _TASK_COUNT_CACHE_LOCK:
|
||||
engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {})
|
||||
if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES:
|
||||
expired_before = moment - _TASK_COUNT_CACHE_TTL_SECONDS
|
||||
for cache_key, (cached_at, _) in list(engine_cache.items()):
|
||||
if cached_at < expired_before:
|
||||
engine_cache.pop(cache_key, None)
|
||||
if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES:
|
||||
engine_cache.pop(next(iter(engine_cache)), None)
|
||||
engine_cache[key] = (moment, total)
|
||||
return total
|
||||
|
||||
|
||||
def _load_task_output_context(
|
||||
db: Session,
|
||||
tasks: list[PlatformFulfillmentTask],
|
||||
) -> _TaskOutputContext:
|
||||
mapping_ids = {
|
||||
int(task.commodity_mapping_id)
|
||||
for task in tasks
|
||||
if task.commodity_mapping_id
|
||||
}
|
||||
commodity_ids = {
|
||||
str(task.commodity_id)
|
||||
for task in tasks
|
||||
if task.commodity_id
|
||||
}
|
||||
account_ids = {int(task.account_id) for task in tasks if task.account_id}
|
||||
lease_ids = {int(task.lease_id) for task in tasks if task.lease_id}
|
||||
bind_task_ids = {int(task.bind_task_id) for task in tasks if task.bind_task_id}
|
||||
task_ids = {int(task.id) for task in tasks}
|
||||
|
||||
mappings = (
|
||||
{
|
||||
int(row.id): row
|
||||
for row in db.query(PlatformCommodityMapping)
|
||||
.filter(PlatformCommodityMapping.id.in_(mapping_ids))
|
||||
.all()
|
||||
}
|
||||
if mapping_ids
|
||||
else {}
|
||||
)
|
||||
goods: dict[str, DouyuGoodsSnapshot] = {}
|
||||
if commodity_ids:
|
||||
for row in (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id.in_(commodity_ids))
|
||||
.order_by(DouyuGoodsSnapshot.id.desc())
|
||||
.all()
|
||||
):
|
||||
goods.setdefault(str(row.commodity_id), row)
|
||||
accounts = (
|
||||
{
|
||||
int(row.id): row
|
||||
for row in db.query(Account).filter(Account.id.in_(account_ids)).all()
|
||||
}
|
||||
if account_ids
|
||||
else {}
|
||||
)
|
||||
leases = (
|
||||
{
|
||||
int(row.id): row
|
||||
for row in db.query(AccountLease)
|
||||
.filter(AccountLease.id.in_(lease_ids))
|
||||
.all()
|
||||
}
|
||||
if lease_ids
|
||||
else {}
|
||||
)
|
||||
bind_tasks = (
|
||||
{
|
||||
int(row.id): row
|
||||
for row in db.query(DouyuTask)
|
||||
.filter(DouyuTask.id.in_(bind_task_ids))
|
||||
.all()
|
||||
}
|
||||
if bind_task_ids
|
||||
else {}
|
||||
)
|
||||
collab_orders: dict[int, DouyuExternalOrder] = {}
|
||||
if task_ids:
|
||||
for row in (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(DouyuExternalOrder.source_task_id.in_(task_ids))
|
||||
.order_by(DouyuExternalOrder.id.desc())
|
||||
.all()
|
||||
):
|
||||
if row.source_task_id is not None:
|
||||
collab_orders.setdefault(int(row.source_task_id), row)
|
||||
return _TaskOutputContext(
|
||||
mappings=mappings,
|
||||
goods=goods,
|
||||
accounts=accounts,
|
||||
leases=leases,
|
||||
bind_tasks=bind_tasks,
|
||||
collab_orders=collab_orders,
|
||||
)
|
||||
|
||||
|
||||
def list_tasks(
|
||||
db: Session,
|
||||
@@ -51,8 +208,9 @@ def list_tasks(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
cutoff = _order_match_started_at(db)
|
||||
query = db.query(PlatformFulfillmentTask)
|
||||
query = _apply_order_match_cutoff(query, _order_match_started_at(db))
|
||||
query = _apply_order_match_cutoff(query, cutoff)
|
||||
query = query.filter(
|
||||
or_(
|
||||
PlatformFulfillmentTask.commodity_mapping_id.isnot(None),
|
||||
@@ -137,7 +295,17 @@ def list_tasks(
|
||||
Account.uid.ilike(pattern),
|
||||
)
|
||||
)
|
||||
total = query.count()
|
||||
total = _cached_task_count(
|
||||
db,
|
||||
query,
|
||||
key=_count_cache_key(
|
||||
cutoff=cutoff,
|
||||
status=status,
|
||||
queue_bucket=queue_bucket,
|
||||
sale_mode=sale_mode,
|
||||
keyword=keyword,
|
||||
),
|
||||
)
|
||||
rows = (
|
||||
query.order_by(
|
||||
PlatformFulfillmentTask.paid_at.desc(),
|
||||
@@ -147,8 +315,9 @@ def list_tasks(
|
||||
.limit(max(1, min(page_size, 100)))
|
||||
.all()
|
||||
)
|
||||
context = _load_task_output_context(db, rows)
|
||||
return {
|
||||
"items": [_task_out(db, row) for row in rows],
|
||||
"items": [_task_out(db, row, context=context) for row in rows],
|
||||
"pagination": {
|
||||
"page": max(1, page),
|
||||
"pageSize": max(1, page_size),
|
||||
@@ -163,19 +332,16 @@ def _task_out(
|
||||
*,
|
||||
include_qr: bool = False,
|
||||
include_exchange_task: bool = False,
|
||||
context: _TaskOutputContext | None = None,
|
||||
) -> dict[str, Any]:
|
||||
resolved = context or _load_task_output_context(db, [task])
|
||||
mapping = (
|
||||
db.query(PlatformCommodityMapping)
|
||||
.filter(PlatformCommodityMapping.id == task.commodity_mapping_id)
|
||||
.first()
|
||||
resolved.mappings.get(int(task.commodity_mapping_id))
|
||||
if task.commodity_mapping_id
|
||||
else None
|
||||
)
|
||||
goods = (
|
||||
db.query(DouyuGoodsSnapshot)
|
||||
.filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id)
|
||||
.order_by(DouyuGoodsSnapshot.id.desc())
|
||||
.first()
|
||||
resolved.goods.get(str(task.commodity_id))
|
||||
if task.commodity_id
|
||||
else None
|
||||
)
|
||||
@@ -186,25 +352,15 @@ def _task_out(
|
||||
or task.internal_sku_key
|
||||
)
|
||||
account = (
|
||||
db.query(Account).filter(Account.id == task.account_id).first()
|
||||
if task.account_id
|
||||
else None
|
||||
)
|
||||
lease = (
|
||||
db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
|
||||
if task.lease_id
|
||||
else None
|
||||
resolved.accounts.get(int(task.account_id)) if task.account_id else None
|
||||
)
|
||||
lease = resolved.leases.get(int(task.lease_id)) if task.lease_id else None
|
||||
bind_task = (
|
||||
db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first()
|
||||
resolved.bind_tasks.get(int(task.bind_task_id))
|
||||
if task.bind_task_id
|
||||
else None
|
||||
)
|
||||
collab_order = (
|
||||
db.query(DouyuExternalOrder)
|
||||
.filter(DouyuExternalOrder.source_task_id == task.id)
|
||||
.first()
|
||||
)
|
||||
collab_order = resolved.collab_orders.get(int(task.id))
|
||||
bind_result = (bind_task.result or {}) if bind_task else {}
|
||||
effective_issue = _effective_binding_issue(task, bind_task, bind_result)
|
||||
effective_last_error = _effective_task_message(task, effective_issue)
|
||||
|
||||
Reference in New Issue
Block a user