perf(fulfillment): 修复 Outbox 状态版本去重、跨进程实时推送与数据库默认配置
This commit is contained in:
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user