perf(fulfillment): 修复 Outbox 状态版本去重、跨进程实时推送与数据库默认配置

This commit is contained in:
yml
2026-11-28 18:52:42 +08:00
parent f23ef42e67
commit d03eeaee18
22 changed files with 751 additions and 72 deletions
+48 -3
View File
@@ -22,7 +22,11 @@ from ..models import (
)
from .account_capability_service import AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED
from .account_protection_service import evaluate_protection_targets
from .account_supply_service import load_supply_snapshot_inventories
from .account_supply_service import (
load_supply_snapshot_inventories,
supply_snapshot_max_age_seconds,
)
from .external_order_source import get_cross_db_lookup_counts
TREND_DAYS = 7
@@ -268,7 +272,11 @@ def _supply_snapshot(
db: Session,
moment: datetime,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
inventories = load_supply_snapshot_inventories(db, now=moment)
inventories = load_supply_snapshot_inventories(
db,
now=moment,
allow_stale_snapshots=True,
)
supply_targets: list[dict[str, Any]] = []
alerts: list[dict[str, Any]] = []
for item in inventories:
@@ -294,6 +302,8 @@ def _supply_snapshot(
"available_shortage": item.available_shortage,
"allocatable_shortage": item.allocatable_shortage,
"needs_replenishment": item.needs_replenishment,
"checked_at": item.checked_at,
"is_stale": item.is_stale,
}
)
if not item.needs_replenishment:
@@ -347,6 +357,29 @@ def _supply_snapshot(
),
}
)
stale_checked_ats = [
item.checked_at
for item in inventories
if item.is_stale and item.checked_at is not None
]
if stale_checked_ats:
oldest_checked_at = min(stale_checked_ats)
age_minutes = max(
1, int((moment - oldest_checked_at).total_seconds() // 60)
)
max_age_minutes = max(1, supply_snapshot_max_age_seconds() // 60)
alerts.append(
{
"code": "supply_snapshot_stale",
"severity": "warning",
"stale_count": len(stale_checked_ats),
"oldest_checked_at": oldest_checked_at,
"message": (
f"账号供给快照已超过 {age_minutes} 分钟未刷新"
f"(阈值 {max_age_minutes} 分钟),当前展示缓存库存"
),
}
)
return supply_targets, alerts
@@ -366,10 +399,19 @@ def account_supply_snapshot(
)
.filter(AccountSupplyTarget.enabled.is_(True))
.scalar()
or moment
)
if checked_at is None:
target_checked = [
item["checked_at"]
for item in supply_targets
if item.get("checked_at") is not None
]
checked_at = max(target_checked) if target_checked else None
is_stale = any(bool(item.get("is_stale")) for item in supply_targets)
return {
"checked_at": checked_at,
"is_stale": is_stale,
"max_age_seconds": supply_snapshot_max_age_seconds(),
"supply_targets": supply_targets,
"alerts": alerts,
}
@@ -653,6 +695,9 @@ def account_platform_status(
"supply_targets": supply_targets,
"alerts": alerts,
"trends": trends,
"cross_db_lookups": (
get_cross_db_lookup_counts() if include_diagnostics else None
),
}
+33 -13
View File
@@ -78,6 +78,8 @@ class SupplyInventory:
covered_shortage: int
available_shortage: int
allocatable_shortage: int
checked_at: datetime | None = None
is_stale: bool = False
@property
def needs_replenishment(self) -> bool:
@@ -271,6 +273,8 @@ def _inventory_from_counts(
covered: int,
available: int,
allocatable: int,
checked_at: datetime | None = None,
is_stale: bool = False,
) -> SupplyInventory:
return SupplyInventory(
target_id=int(target.id),
@@ -300,6 +304,8 @@ def _inventory_from_counts(
+ int(target.safety_buffer or 0)
- allocatable,
),
checked_at=checked_at,
is_stale=is_stale,
)
@@ -461,6 +467,7 @@ def load_supply_snapshot_inventories(
*,
now: datetime | None = None,
refresh_if_stale: bool = True,
allow_stale_snapshots: bool = False,
) -> list[SupplyInventory]:
"""优先读快照;缺失或超过有效期时回源一次并刷新快照。"""
moment = now or datetime.now(UTC)
@@ -478,20 +485,33 @@ def load_supply_snapshot_inventories(
.all()
}
fresh_after = moment - timedelta(seconds=supply_snapshot_max_age_seconds())
if all(
int(target.id) in snapshots
and snapshots[int(target.id)].checked_at >= fresh_after
for target in targets
):
return [
_inventory_from_counts(
target,
covered=int(snapshots[int(target.id)].covered or 0),
available=int(snapshots[int(target.id)].available or 0),
allocatable=int(snapshots[int(target.id)].allocatable or 0),
)
all_present = all(int(target.id) in snapshots for target in targets)
if all_present and (
allow_stale_snapshots
or all(
snapshots[int(target.id)].checked_at >= fresh_after
for target in targets
]
)
):
result: list[SupplyInventory] = []
for target in targets:
snap = snapshots[int(target.id)]
snap_checked_at = (
snap.checked_at
if snap.checked_at.tzinfo is not None
else snap.checked_at.replace(tzinfo=UTC)
)
result.append(
_inventory_from_counts(
target,
covered=int(snap.covered or 0),
available=int(snap.available or 0),
allocatable=int(snap.allocatable or 0),
checked_at=snap_checked_at,
is_stale=snap_checked_at < fresh_after,
)
)
return result
if refresh_if_stale:
return refresh_supply_snapshots(db, now=moment)
return evaluate_supply_targets(db, now=moment)
@@ -21,6 +21,8 @@ from __future__ import annotations
import json
import os
import threading
import time
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -40,6 +42,48 @@ INTERNAL_SHOP_ID = "91kaquan"
_ENGINE: Engine | None = None
_INITIALIZED = False
_LOOKUP_LOCK = threading.Lock()
_LOOKUP_SUMMARY_INTERVAL_SECONDS = 60.0
_LOOKUP_SUMMARY_STEP = 50
_CROSS_DB_LOOKUP_COUNTS: dict[str, int] = {
"lookup_order": 0,
"list_pending_manual": 0,
"item_lookup": 0,
}
_LAST_LOOKUP_SUMMARY_AT = 0.0
_LAST_LOOKUP_SUMMARY_TOTAL = 0
def _record_cross_db_lookup(path: str, detail: str) -> None:
global _LAST_LOOKUP_SUMMARY_AT, _LAST_LOOKUP_SUMMARY_TOTAL
now_mono = time.monotonic()
should_summarize = False
snapshot: dict[str, int] | None = None
with _LOOKUP_LOCK:
_CROSS_DB_LOOKUP_COUNTS[path] = _CROSS_DB_LOOKUP_COUNTS.get(path, 0) + 1
path_total = _CROSS_DB_LOOKUP_COUNTS[path]
grand_total = sum(_CROSS_DB_LOOKUP_COUNTS.values())
if (
grand_total - _LAST_LOOKUP_SUMMARY_TOTAL >= _LOOKUP_SUMMARY_STEP
or now_mono - _LAST_LOOKUP_SUMMARY_AT >= _LOOKUP_SUMMARY_INTERVAL_SECONDS
):
_LAST_LOOKUP_SUMMARY_AT = now_mono
_LAST_LOOKUP_SUMMARY_TOTAL = grand_total
should_summarize = True
snapshot = dict(_CROSS_DB_LOOKUP_COUNTS)
logger.debug(
"order_site 跨库只读回查 path={} path_hits={} detail={}",
path,
path_total,
detail,
)
if should_summarize and snapshot is not None:
logger.info("order_site 跨库只读回查累计计数 counts={}", snapshot)
def get_cross_db_lookup_counts() -> dict[str, int]:
with _LOOKUP_LOCK:
return dict(_CROSS_DB_LOOKUP_COUNTS)
class OrderLookupUnavailable(Exception):
@@ -144,6 +188,7 @@ def _fetch_rows(order_no: str) -> list[dict[str, Any]]:
"""
)
try:
_record_cross_db_lookup("lookup_order", f"order_no={order_no}")
with engine.connect() as conn:
return [
dict(row)
@@ -222,6 +267,7 @@ def _fetch_pending_manual_fulfillments(
"""
)
try:
_record_cross_db_lookup("list_pending_manual", f"limit={limit}")
with engine.connect() as conn:
params: dict[str, Any] = {
"limit": max(1, min(limit, 500)),
@@ -341,6 +387,7 @@ def lookup_pending_manual_fulfillment(
"""
)
try:
_record_cross_db_lookup("item_lookup", f"source_order_item_id={item_id}")
with _get_engine().connect() as conn:
row = (
conn.execute(sql, {"source_order_item_id": int(item_id)})
@@ -60,6 +60,7 @@ from .binding_status import (
_customer_task_message,
)
from .common import FLOW_VERSION_CLEAN, SCOPE_ELITE, _has_game_home_profile, _now
from .order_site_notifier import binding_state_hash
from .outbox import _emit_order_site_binding_state
from .repository import (
_binding_qr_expired,
@@ -2070,28 +2071,44 @@ def reconcile_binding_state_outbox(
limit: int = 500,
after_task_id: int = 0,
) -> dict[str, Any]:
"""按 ID 游标补齐 active 快照;批次只限制吞吐,不形成永久扫描窗口。"""
"""只读筛查漂移的 clean_v1 活跃任务再按需加锁写 Outbox;历史冻结单不参与。"""
from .views import customer_binding_out
batch_size = max(1, min(limit, 500))
normalized_after = max(0, int(after_task_id or 0))
task_ids = [
int(row.id)
for row in (
db.query(PlatformFulfillmentTask.id)
.filter(
PlatformFulfillmentTask.id > normalized_after,
PlatformFulfillmentTask.execution_status.notin_(
["completed", "cancelled"]
),
)
.order_by(PlatformFulfillmentTask.id.asc())
.limit(batch_size)
.all()
candidates = (
db.query(
PlatformFulfillmentTask.id,
PlatformFulfillmentTask.last_emitted_state_hash,
)
]
queued = sum(
1 for task_id in task_ids if _emit_order_site_binding_state(db, task_id)
.filter(
PlatformFulfillmentTask.id > normalized_after,
PlatformFulfillmentTask.flow_version == FLOW_VERSION_CLEAN,
PlatformFulfillmentTask.execution_status.notin_(
["completed", "cancelled"]
),
)
.order_by(PlatformFulfillmentTask.id.asc())
.limit(batch_size)
.all()
)
db.commit()
task_ids = [int(row.id) for row in candidates]
drifted_ids: list[int] = []
for row in candidates:
task_id = int(row.id)
last_hash = str(row.last_emitted_state_hash or "")
if not last_hash:
drifted_ids.append(task_id)
continue
payload = customer_binding_out(db, task_id)
if binding_state_hash(payload) != last_hash:
drifted_ids.append(task_id)
queued = sum(
1 for task_id in drifted_ids if _emit_order_site_binding_state(db, task_id)
)
if queued:
db.commit()
return {
"queued": queued,
"nextTaskId": max(task_ids, default=normalized_after),
@@ -0,0 +1,119 @@
"""直播账号履约工作台实时事件总线:事务提交后广播 + 独立 worker 游标桥接。"""
from __future__ import annotations
import asyncio
import threading
from loguru import logger
from sqlalchemy import event, func
from sqlalchemy.orm import Session
from ...database import SessionLocal
from ...models import IntegrationOutbox, PlatformFulfillmentEvent
from ..douyu_collab_events import CollabEventHub
_PENDING_EVENTS_KEY = "_pending_platform_fulfillment_events"
_HOOK_REGISTERED_KEY = "_platform_fulfillment_event_hooked"
_RELAY_LOCK = threading.Lock()
_relay_task: asyncio.Task[None] | None = None
class PlatformFulfillmentEventHub(CollabEventHub):
"""在 CollabEventHub 基础上暴露活跃订阅者数量,按需启停跨进程监听。"""
def subscriber_count(self) -> int:
with self._lock:
return len(self._subscribers)
platform_fulfillment_events = PlatformFulfillmentEventHub()
def publish_after_commit(
db: Session,
*,
scope: str,
action: str,
actor_id: int | None = None,
) -> None:
"""在当前事务真正 COMMIT 后发布失效事件,回滚时自动丢弃。"""
pending = db.info.setdefault(_PENDING_EVENTS_KEY, [])
pending.append((scope, action, actor_id))
if db.info.get(_HOOK_REGISTERED_KEY):
return
def _flush_after_commit(session: Session) -> None:
items = session.info.pop(_PENDING_EVENTS_KEY, [])
for ev_scope, ev_action, ev_actor_id in items:
platform_fulfillment_events.publish(
scope=ev_scope,
action=ev_action,
actor_id=ev_actor_id,
)
def _clear_on_rollback(session: Session, *_args: object) -> None:
session.info.pop(_PENDING_EVENTS_KEY, None)
event.listen(db, "after_commit", _flush_after_commit)
event.listen(db, "after_rollback", _clear_on_rollback)
event.listen(db, "after_soft_rollback", _clear_on_rollback)
db.info[_HOOK_REGISTERED_KEY] = True
def _read_db_watermarks() -> tuple[int, int]:
"""用主键 MAX(id) 极低开销探测独立 worker 进程的新增提交。"""
with SessionLocal() as session:
max_event_id = int(
session.query(func.coalesce(func.max(PlatformFulfillmentEvent.id), 0)).scalar()
or 0
)
max_outbox_id = int(
session.query(func.coalesce(func.max(IntegrationOutbox.id), 0)).scalar()
or 0
)
return max_event_id, max_outbox_id
async def _worker_event_relay_loop(interval_seconds: float = 2.0) -> None:
try:
last_seen = await asyncio.to_thread(_read_db_watermarks)
except Exception as exc: # noqa: BLE001 - 跨进程探针异常不得中断 WebSocket 监听
logger.debug("初始化履约跨进程事件游标失败:{}", exc)
last_seen = (0, 0)
while platform_fulfillment_events.subscriber_count() > 0:
await asyncio.sleep(interval_seconds)
if platform_fulfillment_events.subscriber_count() <= 0:
break
try:
current = await asyncio.to_thread(_read_db_watermarks)
except Exception as exc: # noqa: BLE001 - 短暂库波动下一轮继续探测
logger.debug("探测履约跨进程事件游标失败:{}", exc)
continue
if current != last_seen:
last_seen = current
platform_fulfillment_events.publish(
scope="tasks",
action="worker.state_changed",
)
def ensure_worker_event_relay() -> None:
"""有前端 WebSocket 订阅者时开启共享跨进程 DB 游标监听,断开后自动停止。"""
global _relay_task
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return
with _RELAY_LOCK:
if _relay_task is None or _relay_task.done():
_relay_task = loop.create_task(_worker_event_relay_loop())
__all__ = [
"PlatformFulfillmentEventHub",
"ensure_worker_event_relay",
"platform_fulfillment_events",
"publish_after_commit",
]
@@ -13,7 +13,7 @@ from ..integration.outbox import enqueue_integration_event
EVENT_TYPE = "platform_fulfillment.binding_state_changed"
def _state_dedupe_key(payload: dict[str, Any]) -> str:
def binding_state_hash(payload: dict[str, Any]) -> str:
state = {
"sessionId": payload.get("sessionId"),
"executionStatus": payload.get("executionStatus"),
@@ -33,10 +33,16 @@ def _state_dedupe_key(payload: dict[str, Any]) -> str:
"queueLane": payload.get("queueLane"),
"customerProfileReset": payload.get("customerProfileReset"),
}
digest = hashlib.sha256(
return hashlib.sha256(
json.dumps(state, ensure_ascii=False, sort_keys=True).encode("utf-8")
).hexdigest()[:32]
return f"binding-state:{payload.get('sessionId')}:{digest}"
def _state_dedupe_key(payload: dict[str, Any]) -> str:
state_version = int(payload.get("stateVersion") or 0)
if state_version > 0:
return f"binding-state:{payload.get('sessionId')}:v{state_version}"
return f"binding-state:{payload.get('sessionId')}:{binding_state_hash(payload)}"
def enqueue_order_site_binding_state(
@@ -53,4 +59,4 @@ def enqueue_order_site_binding_state(
)
__all__ = ["enqueue_order_site_binding_state"]
__all__ = ["binding_state_hash", "enqueue_order_site_binding_state"]
@@ -9,7 +9,11 @@ from sqlalchemy.orm import Session
from ...models import (
PlatformFulfillmentTask,
)
from .order_site_notifier import enqueue_order_site_binding_state
from .events import publish_after_commit
from .order_site_notifier import (
binding_state_hash,
enqueue_order_site_binding_state,
)
from .views import customer_binding_out
@@ -26,16 +30,26 @@ def _emit_order_site_binding_state(
.with_for_update()
.one()
)
next_state_version = int(task.state_version or 0) + 1
payload = customer_binding_out(db, task_id)
payload["stateVersion"] = next_state_version
if extra:
payload.update(extra)
state_hash = binding_state_hash(payload)
if not extra and (task.last_emitted_state_hash or "") == state_hash:
return False
next_state_version = int(task.state_version or 0) + 1
payload["stateVersion"] = next_state_version
enqueued = enqueue_order_site_binding_state(
db,
payload,
)
if enqueued:
task.state_version = next_state_version
task.last_emitted_state_hash = state_hash
db.flush()
publish_after_commit(
db,
scope="tasks",
action="binding_state_emitted",
)
return enqueued
@@ -9,7 +9,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import or_
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from ...models import (
@@ -106,7 +106,12 @@ def _cached_task_count(
cached = engine_cache.get(key)
if cached and moment - cached[0] < _TASK_COUNT_CACHE_TTL_SECONDS:
return cached[1]
total = int(query.count())
total = int(
query.order_by(None)
.with_entities(func.count(PlatformFulfillmentTask.id))
.scalar()
or 0
)
with _TASK_COUNT_CACHE_LOCK:
engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {})
if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES: