perf(fulfillment): 修复 Outbox 状态版本去重、跨进程实时推送与数据库默认配置
This commit is contained in:
+5
-5
@@ -80,8 +80,8 @@ DOUYU_LOGIN_MEM_LIMIT=2g
|
||||
DOUYU_LOGIN_CPUS=2
|
||||
MYSQL_MEM_LIMIT=3g
|
||||
MYSQL_CPUS=2
|
||||
# MySQL 性能观测;同机部署资源紧张时可先使用 256M。
|
||||
MYSQL_INNODB_BUFFER_POOL_SIZE=512M
|
||||
# MySQL 性能观测;默认 1G(容器限额 3G),同机部署资源紧张时可调低。
|
||||
MYSQL_INNODB_BUFFER_POOL_SIZE=1G
|
||||
MYSQL_INNODB_REDO_LOG_CAPACITY=512M
|
||||
# binlog 保留 12 小时;当前无副本,避免 1GiB 级 binlog 长期占满磁盘。
|
||||
MYSQL_BINLOG_EXPIRE_LOGS_SECONDS=43200
|
||||
@@ -103,11 +103,11 @@ DEV_DB_PORT=3307
|
||||
|
||||
# 数据库连接策略(仅 MySQL 生效)
|
||||
# null=每次 Session 关闭即断开物理连接;queue=复用连接池。
|
||||
DB_POOL_MODE=null
|
||||
WORKER_DB_POOL_MODE=null
|
||||
DB_POOL_MODE=queue
|
||||
WORKER_DB_POOL_MODE=queue
|
||||
DB_POOL_SIZE=20
|
||||
DB_MAX_OVERFLOW=20
|
||||
WORKER_DB_POOL_SIZE=12
|
||||
WORKER_DB_POOL_SIZE=10
|
||||
WORKER_DB_MAX_OVERFLOW=4
|
||||
DEPLOY_STARTUP_TIMEOUT_SECONDS=1800
|
||||
DB_POOL_TIMEOUT=30
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 直播账号运营后台
|
||||
|
||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.6)。
|
||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.8)。
|
||||
|
||||
## 能做什么
|
||||
|
||||
|
||||
+5
-5
@@ -37,14 +37,14 @@ services:
|
||||
- DB_USER=${MYSQL_USER:-douyu_login}
|
||||
- DB_PASSWORD=${MYSQL_PASSWORD:?请在 .env 中设置 MYSQL_PASSWORD}
|
||||
# null=Session.close 立即断开物理连接;queue=保留连接池复用。
|
||||
- DB_POOL_MODE=${DB_POOL_MODE:-null}
|
||||
- DB_POOL_MODE=${DB_POOL_MODE:-queue}
|
||||
- DB_POOL_SIZE=${DB_POOL_SIZE:-20}
|
||||
- DB_MAX_OVERFLOW=${DB_MAX_OVERFLOW:-20}
|
||||
- DB_POOL_TIMEOUT=${DB_POOL_TIMEOUT:-30}
|
||||
- DB_POOL_RECYCLE=${DB_POOL_RECYCLE:-1800}
|
||||
- DB_LOCK_WAIT_TIMEOUT=${DB_LOCK_WAIT_TIMEOUT:-10}
|
||||
- WORKER_DB_POOL_MODE=${WORKER_DB_POOL_MODE:-null}
|
||||
- WORKER_DB_POOL_SIZE=${WORKER_DB_POOL_SIZE:-12}
|
||||
- WORKER_DB_POOL_MODE=${WORKER_DB_POOL_MODE:-queue}
|
||||
- WORKER_DB_POOL_SIZE=${WORKER_DB_POOL_SIZE:-10}
|
||||
- WORKER_DB_MAX_OVERFLOW=${WORKER_DB_MAX_OVERFLOW:-4}
|
||||
- WORKER_DB_POOL_TIMEOUT=${WORKER_DB_POOL_TIMEOUT:-30}
|
||||
- DOUYU_BATCH_CREATE_CONCURRENCY=${DOUYU_BATCH_CREATE_CONCURRENCY:-4}
|
||||
@@ -203,8 +203,8 @@ services:
|
||||
# 查询静默返回空、看着像「没数据」。全库无 TIMESTAMP 列、也没有
|
||||
# CURRENT_TIMESTAMP 默认值,因此改这里不会改变任何已有数据的语义。
|
||||
- --default-time-zone=+00:00
|
||||
# 业务表已超过 300MiB;可通过 .env 调整,默认给 MySQL 512MiB 缓冲池。
|
||||
- --innodb-buffer-pool-size=${MYSQL_INNODB_BUFFER_POOL_SIZE:-512M}
|
||||
# 业务表已超过 300MiB;可通过 .env 调整,默认给 MySQL 1G 缓冲池。
|
||||
- --innodb-buffer-pool-size=${MYSQL_INNODB_BUFFER_POOL_SIZE:-1G}
|
||||
# 100MiB redo 在高写入时出现过 checkpointer 落后告警,默认提升到 512MiB。
|
||||
- --innodb-redo-log-capacity=${MYSQL_INNODB_REDO_LOG_CAPACITY:-512M}
|
||||
# 当前库没有副本;12 小时足以覆盖短期误操作,又不会在高峰期挤满磁盘。
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "live-hub-py"
|
||||
version = "0.4.6"
|
||||
version = "0.4.8"
|
||||
description = "直播账号运营 Web 后台"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
|
||||
@@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261128_0136"
|
||||
HEAD_REVISION = "20261128_0137"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
@@ -94,6 +94,7 @@ _LATER_ORM_COLUMNS = {
|
||||
"customer_home_images": "JSON NULL",
|
||||
"customer_profile_updated_at": "DATETIME NULL",
|
||||
"flow_version": "INTEGER NOT NULL DEFAULT 1",
|
||||
"last_emitted_state_hash": "VARCHAR(64) NOT NULL DEFAULT ''",
|
||||
},
|
||||
"douyu_external_orders": {
|
||||
"succeeded_at": "DATETIME NULL",
|
||||
|
||||
@@ -175,3 +175,249 @@ def test_auto_order_sync_is_throttled(monkeypatch):
|
||||
"fetched": 1
|
||||
}
|
||||
assert calls == [100, 100]
|
||||
|
||||
|
||||
def test_emit_binding_state_allows_a_b_a_and_skips_same_hash(db):
|
||||
from web.backend.models import IntegrationOutbox
|
||||
from web.backend.services.platform_fulfillment import binding, outbox
|
||||
|
||||
task = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="order-aba",
|
||||
source_order_item_id="item-aba",
|
||||
platform_order_id="DY-ABA-1",
|
||||
sku_name="斗鱼精英宝典",
|
||||
quantity=1,
|
||||
flow_version=binding.FLOW_VERSION_CLEAN,
|
||||
binding_status="unallocated",
|
||||
execution_status="pending",
|
||||
)
|
||||
db.add(task)
|
||||
db.commit()
|
||||
|
||||
assert outbox._emit_order_site_binding_state(db, task.id) is True
|
||||
db.commit()
|
||||
db.refresh(task)
|
||||
assert task.state_version == 1
|
||||
assert task.last_emitted_state_hash
|
||||
|
||||
assert outbox._emit_order_site_binding_state(db, task.id) is False
|
||||
assert (
|
||||
db.query(IntegrationOutbox)
|
||||
.filter(IntegrationOutbox.dedupe_key.like(f"binding-state:{task.id}:%"))
|
||||
.count()
|
||||
== 1
|
||||
)
|
||||
|
||||
task.binding_status = "qr_pending"
|
||||
db.flush()
|
||||
assert outbox._emit_order_site_binding_state(db, task.id) is True
|
||||
|
||||
task.binding_status = "unallocated"
|
||||
db.flush()
|
||||
assert outbox._emit_order_site_binding_state(db, task.id) is True
|
||||
db.commit()
|
||||
db.refresh(task)
|
||||
|
||||
assert task.state_version == 3
|
||||
keys = [
|
||||
row.dedupe_key
|
||||
for row in db.query(IntegrationOutbox)
|
||||
.filter(IntegrationOutbox.dedupe_key.like(f"binding-state:{task.id}:%"))
|
||||
.order_by(IntegrationOutbox.id.asc())
|
||||
.all()
|
||||
]
|
||||
assert keys == [
|
||||
f"binding-state:{task.id}:v1",
|
||||
f"binding-state:{task.id}:v2",
|
||||
f"binding-state:{task.id}:v3",
|
||||
]
|
||||
|
||||
|
||||
def test_reconcile_binding_state_outbox_skips_legacy_and_unchanged_clean_tasks(db):
|
||||
from web.backend.models import IntegrationOutbox
|
||||
from web.backend.services.platform_fulfillment import binding, common, views
|
||||
|
||||
legacy = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="order-legacy",
|
||||
source_order_item_id="item-legacy",
|
||||
platform_order_id="DY-LEGACY-1",
|
||||
sku_name="斗鱼精英宝典",
|
||||
quantity=1,
|
||||
flow_version=common.FLOW_VERSION_LEGACY,
|
||||
binding_status="unallocated",
|
||||
execution_status="pending",
|
||||
)
|
||||
unchanged = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="order-clean-ok",
|
||||
source_order_item_id="item-clean-ok",
|
||||
platform_order_id="DY-CLEAN-OK",
|
||||
sku_name="斗鱼精英宝典",
|
||||
quantity=1,
|
||||
flow_version=binding.FLOW_VERSION_CLEAN,
|
||||
binding_status="unallocated",
|
||||
execution_status="pending",
|
||||
state_version=1,
|
||||
)
|
||||
drifted = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="order-clean-drift",
|
||||
source_order_item_id="item-clean-drift",
|
||||
platform_order_id="DY-CLEAN-DRIFT",
|
||||
sku_name="斗鱼精英宝典",
|
||||
quantity=1,
|
||||
flow_version=binding.FLOW_VERSION_CLEAN,
|
||||
binding_status="qr_pending",
|
||||
execution_status="waiting_bind",
|
||||
state_version=1,
|
||||
last_emitted_state_hash="outdated-hash",
|
||||
)
|
||||
db.add_all([legacy, unchanged, drifted])
|
||||
db.flush()
|
||||
unchanged.last_emitted_state_hash = binding.binding_state_hash(
|
||||
views.customer_binding_out(db, unchanged.id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
result = service.reconcile_binding_state_outbox(db, limit=100)
|
||||
assert result["queued"] == 1
|
||||
|
||||
queued_keys = {
|
||||
row.dedupe_key
|
||||
for row in db.query(IntegrationOutbox).all()
|
||||
}
|
||||
assert f"binding-state:{drifted.id}:v2" in queued_keys
|
||||
assert not any(k.startswith(f"binding-state:{legacy.id}:") for k in queued_keys)
|
||||
assert not any(k.startswith(f"binding-state:{unchanged.id}:") for k in queued_keys)
|
||||
|
||||
|
||||
def test_load_supply_snapshot_inventories_allows_stale_snapshots(db, monkeypatch):
|
||||
from web.backend.models import AccountSupplySnapshot, AccountSupplyTarget
|
||||
from web.backend.services import account_observability, account_supply_service
|
||||
|
||||
target = AccountSupplyTarget(
|
||||
platform="douyu",
|
||||
scope="elite",
|
||||
commodity_id="",
|
||||
value_class="normal",
|
||||
target_covered=10,
|
||||
target_available=5,
|
||||
target_allocatable=5,
|
||||
safety_buffer=1,
|
||||
enabled=True,
|
||||
)
|
||||
db.add(target)
|
||||
db.flush()
|
||||
stale_at = (datetime.now(UTC) - timedelta(hours=2)).replace(microsecond=0)
|
||||
snapshot = AccountSupplySnapshot(
|
||||
target_id=target.id,
|
||||
covered=12,
|
||||
available=7,
|
||||
allocatable=6,
|
||||
checked_at=stale_at,
|
||||
)
|
||||
db.add(snapshot)
|
||||
db.commit()
|
||||
|
||||
def _boom(*_args, **_kwargs):
|
||||
raise AssertionError("stale HTTP snapshot read must not recompute supply")
|
||||
|
||||
monkeypatch.setattr(account_supply_service, "refresh_supply_snapshots", _boom)
|
||||
monkeypatch.setattr(account_supply_service, "evaluate_supply_targets", _boom)
|
||||
|
||||
inventories = account_supply_service.load_supply_snapshot_inventories(
|
||||
db,
|
||||
allow_stale_snapshots=True,
|
||||
)
|
||||
assert len(inventories) == 1
|
||||
assert inventories[0].covered == 12
|
||||
assert inventories[0].available == 7
|
||||
assert inventories[0].allocatable == 6
|
||||
assert inventories[0].is_stale is True
|
||||
assert inventories[0].checked_at == stale_at
|
||||
|
||||
http_snapshot = account_observability.account_supply_snapshot(db)
|
||||
assert http_snapshot["is_stale"] is True
|
||||
assert http_snapshot["checked_at"] == stale_at
|
||||
assert any(
|
||||
alert.get("code") == "supply_snapshot_stale"
|
||||
for alert in http_snapshot["alerts"]
|
||||
)
|
||||
|
||||
|
||||
def test_cross_db_lookup_telemetry_and_cached_task_count(db):
|
||||
from web.backend.services import account_observability, external_order_source
|
||||
from web.backend.services.platform_fulfillment import views
|
||||
|
||||
before = external_order_source.get_cross_db_lookup_counts().get("item_lookup", 0)
|
||||
external_order_source._record_cross_db_lookup("item_lookup", "sample")
|
||||
after = external_order_source.get_cross_db_lookup_counts().get("item_lookup", 0)
|
||||
assert after == before + 1
|
||||
status = account_observability.account_platform_status(
|
||||
db,
|
||||
include_trends=False,
|
||||
include_supply=False,
|
||||
include_diagnostics=True,
|
||||
)
|
||||
assert status["cross_db_lookups"]["item_lookup"] == after
|
||||
|
||||
task = PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="order-count",
|
||||
source_order_item_id="item-count",
|
||||
platform_order_id="DY-COUNT-1",
|
||||
sku_name="斗鱼精英宝典",
|
||||
quantity=1,
|
||||
)
|
||||
db.add(task)
|
||||
db.commit()
|
||||
|
||||
views.invalidate_task_list_count_cache()
|
||||
total = views._cached_task_count(
|
||||
db,
|
||||
db.query(PlatformFulfillmentTask),
|
||||
key=("unit", "all"),
|
||||
)
|
||||
assert total >= 1
|
||||
|
||||
|
||||
def test_publish_after_commit_only_fires_on_commit(db, monkeypatch):
|
||||
from web.backend.services.platform_fulfillment import events
|
||||
|
||||
published: list[tuple[str, str, int | None]] = []
|
||||
monkeypatch.setattr(
|
||||
events.platform_fulfillment_events,
|
||||
"publish",
|
||||
lambda *, scope, action, actor_id=None: published.append(
|
||||
(scope, action, actor_id)
|
||||
)
|
||||
or {},
|
||||
)
|
||||
|
||||
events.publish_after_commit(db, scope="tasks", action="rollback_no_sql")
|
||||
assert published == []
|
||||
db.rollback()
|
||||
assert published == []
|
||||
|
||||
db.add(
|
||||
PlatformFulfillmentTask(
|
||||
source_system="order_site",
|
||||
source_order_id="order-rb",
|
||||
source_order_item_id="item-rb",
|
||||
platform_order_id="DY-RB-1",
|
||||
sku_name="斗鱼精英宝典",
|
||||
quantity=1,
|
||||
)
|
||||
)
|
||||
db.flush()
|
||||
events.publish_after_commit(db, scope="tasks", action="rollback_with_sql")
|
||||
db.rollback()
|
||||
assert published == []
|
||||
|
||||
events.publish_after_commit(db, scope="tasks", action="commit_test", actor_id=7)
|
||||
db.flush()
|
||||
assert published == []
|
||||
db.commit()
|
||||
assert published == [("tasks", "commit_test", 7)]
|
||||
|
||||
@@ -381,7 +381,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "live-hub-py"
|
||||
version = "0.4.6"
|
||||
version = "0.4.8"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "alembic" },
|
||||
|
||||
@@ -545,6 +545,10 @@
|
||||
"20261128_0136_fulfillment_allocation_policy.py": {
|
||||
"revision": "20261128_0136",
|
||||
"sha256": "d92e34a71c7b39a018636b41f21230d73013e6d6361d1a3f231cf0091c827d7e"
|
||||
},
|
||||
"20261128_0137_platform_fulfillment_outbox_state_hash.py": {
|
||||
"revision": "20261128_0137",
|
||||
"sha256": "a1ac06c57eacf11d12d75ec7a6bc9099fcafd33d6119ecdb94fd17abe99dc660"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
"""为平台履约任务增加 Outbox 状态摘要字段以支持 A-B-A 幂等推进。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261128_0137"
|
||||
down_revision: str | None = "20261128_0136"
|
||||
branch_labels: str | None = None
|
||||
depends_on: str | None = None
|
||||
|
||||
TABLE = "platform_fulfillment_tasks"
|
||||
COLUMN = "last_emitted_state_hash"
|
||||
|
||||
|
||||
def _column_exists(name: str) -> bool:
|
||||
conn = op.get_bind()
|
||||
count = conn.execute(
|
||||
sa.text(
|
||||
"SELECT COUNT(*) FROM information_schema.columns "
|
||||
"WHERE table_schema = DATABASE() AND table_name = :table "
|
||||
"AND column_name = :name"
|
||||
),
|
||||
{"table": TABLE, "name": name},
|
||||
).scalar()
|
||||
return bool(count)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if not _column_exists(COLUMN):
|
||||
op.add_column(
|
||||
TABLE,
|
||||
sa.Column(
|
||||
COLUMN,
|
||||
sa.String(length=64),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if _column_exists(COLUMN):
|
||||
op.drop_column(TABLE, COLUMN)
|
||||
@@ -2522,6 +2522,9 @@ class PlatformFulfillmentTask(Base):
|
||||
state_version: Mapped[int] = mapped_column(
|
||||
BigInteger, nullable=False, default=0, server_default="0"
|
||||
)
|
||||
last_emitted_state_hash: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, default="", server_default=""
|
||||
)
|
||||
last_error: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
source_snapshot_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
operator_id: Mapped[int | None] = mapped_column(
|
||||
|
||||
@@ -2,14 +2,23 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
HTTPException,
|
||||
Query,
|
||||
WebSocket,
|
||||
WebSocketDisconnect,
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import require_permission
|
||||
from ..deps import authenticate_websocket, require_permission
|
||||
from ..models import User
|
||||
from ..permissions import get_user_permissions
|
||||
from ..schemas import (
|
||||
PlatformFulfillmentCollabSyncRequest,
|
||||
PlatformFulfillmentCompleteRequest,
|
||||
@@ -24,10 +33,38 @@ from ..services import douyu_collab_service
|
||||
from ..services.audit_service import record_audit
|
||||
from ..services.douyu_collab_events import collab_events
|
||||
from ..services.platform_fulfillment import service
|
||||
from ..services.platform_fulfillment.events import (
|
||||
ensure_worker_event_relay,
|
||||
platform_fulfillment_events,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/platform-fulfillment", tags=["直播账号履约"])
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws_platform_fulfillment(websocket: WebSocket):
|
||||
"""直播账号履约工作台实时失效通知:前端收到后静默重拉列表与详情。"""
|
||||
user = authenticate_websocket(websocket)
|
||||
if not user or "platform_fulfillment:view" not in get_user_permissions(user):
|
||||
await websocket.close(code=1008, reason="未授权")
|
||||
return
|
||||
await websocket.accept()
|
||||
queue = platform_fulfillment_events.subscribe()
|
||||
ensure_worker_event_relay()
|
||||
try:
|
||||
await websocket.send_json(platform_fulfillment_events.ready_event())
|
||||
while True:
|
||||
try:
|
||||
event = await asyncio.wait_for(queue.get(), timeout=25)
|
||||
await websocket.send_json(event)
|
||||
except TimeoutError:
|
||||
await websocket.send_json(platform_fulfillment_events.ping_event())
|
||||
except (WebSocketDisconnect, RuntimeError):
|
||||
pass
|
||||
finally:
|
||||
platform_fulfillment_events.unsubscribe(queue)
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
def get_settings(
|
||||
db: Session = Depends(get_db),
|
||||
@@ -132,6 +169,11 @@ def sync_tasks(
|
||||
)
|
||||
|
||||
invalidate_task_list_count_cache()
|
||||
platform_fulfillment_events.publish(
|
||||
scope="tasks",
|
||||
action="task.sync",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -587,6 +629,11 @@ def complete_task(
|
||||
detail={"note": req.note},
|
||||
)
|
||||
db.commit()
|
||||
platform_fulfillment_events.publish(
|
||||
scope="tasks",
|
||||
action="task.complete",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -607,6 +654,11 @@ def release_task(
|
||||
detail={},
|
||||
)
|
||||
db.commit()
|
||||
platform_fulfillment_events.publish(
|
||||
scope="tasks",
|
||||
action="task.release",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -631,6 +683,11 @@ def release_task_to_manual(
|
||||
detail={"reason": req.reason},
|
||||
)
|
||||
db.commit()
|
||||
platform_fulfillment_events.publish(
|
||||
scope="tasks",
|
||||
action="task.release_manual",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -655,6 +712,11 @@ def mark_manual(
|
||||
detail={"reason": req.reason},
|
||||
)
|
||||
db.commit()
|
||||
platform_fulfillment_events.publish(
|
||||
scope="tasks",
|
||||
action="task.manual",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -679,6 +741,11 @@ def cancel_task(
|
||||
detail={"reason": req.reason},
|
||||
)
|
||||
db.commit()
|
||||
platform_fulfillment_events.publish(
|
||||
scope="tasks",
|
||||
action="task.cancel",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -708,6 +775,11 @@ def restore_cancelled_task(
|
||||
action="order.restore_from_platform_fulfillment",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
platform_fulfillment_events.publish(
|
||||
scope="tasks",
|
||||
action="task.restore",
|
||||
actor_id=int(current.id),
|
||||
)
|
||||
from ..services.platform_fulfillment.auto_allocator import wake_auto_allocator
|
||||
|
||||
wake_auto_allocator([task_id])
|
||||
|
||||
@@ -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
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -813,6 +813,8 @@ export interface DouyuSupplyTargetStatus {
|
||||
available_shortage: number;
|
||||
allocatable_shortage: number;
|
||||
needs_replenishment: boolean;
|
||||
checked_at?: string | null;
|
||||
is_stale?: boolean;
|
||||
}
|
||||
|
||||
export interface DouyuSupplyTargetConfig {
|
||||
@@ -951,7 +953,9 @@ export interface DouyuPlatformTrendsResponse {
|
||||
}
|
||||
|
||||
export interface DouyuAccountPlatformSupply {
|
||||
checked_at: string;
|
||||
checked_at: string | null;
|
||||
is_stale?: boolean;
|
||||
max_age_seconds?: number;
|
||||
supply_targets: DouyuSupplyTargetStatus[];
|
||||
alerts: DouyuPlatformAlert[];
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { getErrorMessage } from '../utils/error';
|
||||
import { message } from '../utils/antdMessage';
|
||||
import { formatTime } from '../utils/time';
|
||||
import { getUser } from '../store/auth';
|
||||
import { useCollabRealtime } from '../hooks/useCollabRealtime';
|
||||
import { usePermissions } from '../hooks/usePermissions';
|
||||
|
||||
const { Text, Title } = Typography;
|
||||
@@ -699,16 +700,42 @@ export default function PlatformFulfillmentPage() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const [realtimePending, setRealtimePending] = useState(false);
|
||||
|
||||
const { connected: realtimeConnected } = useCollabRealtime({
|
||||
enabled: true,
|
||||
path: '/api/platform-fulfillment/ws',
|
||||
onInvalidate: () => {
|
||||
setRealtimePending(true);
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
void loadTasks();
|
||||
}, [loadTasks]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!realtimePending) return undefined;
|
||||
const timer = window.setTimeout(() => {
|
||||
setRealtimePending(false);
|
||||
if (document.visibilityState === 'visible') {
|
||||
void loadTasks(true);
|
||||
if (selectedId) void loadDetail(selectedId, true);
|
||||
}
|
||||
}, 300);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [realtimePending, loadTasks, loadDetail, selectedId]);
|
||||
|
||||
// 实时通道正常时仅做 60s 跨进程兜底;断线时降级为 15s 轮询,取消 10s/5s 高频轮询。
|
||||
useEffect(() => {
|
||||
const intervalMs = realtimeConnected ? 60_000 : 15_000;
|
||||
const timer = window.setInterval(() => {
|
||||
if (document.visibilityState === 'visible') void loadTasks(true);
|
||||
}, 10000);
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
void loadTasks(true);
|
||||
if (selectedId) void loadDetail(selectedId, true);
|
||||
}, intervalMs);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [loadTasks]);
|
||||
}, [realtimeConnected, loadTasks, loadDetail, selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
void platformFulfillmentApi
|
||||
@@ -721,14 +748,6 @@ export default function PlatformFulfillmentPage() {
|
||||
if (selectedId) void loadDetail(selectedId);
|
||||
}, [loadDetail, selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedId) return;
|
||||
const timer = window.setInterval(() => {
|
||||
if (document.visibilityState === 'visible') void loadDetail(selectedId, true);
|
||||
}, 5000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [loadDetail, selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!douyuActionBatchId) return;
|
||||
let stopped = false;
|
||||
|
||||
@@ -161,6 +161,8 @@ export default function AccountPlatformStatusPanel() {
|
||||
const [targetConfigs, setTargetConfigs] = useState<DouyuSupplyTargetConfig[]>([]);
|
||||
const [supplyTargets, setSupplyTargets] = useState<DouyuSupplyTargetStatus[]>([]);
|
||||
const [supplyAlerts, setSupplyAlerts] = useState<DouyuPlatformAlert[]>([]);
|
||||
const [supplyCheckedAt, setSupplyCheckedAt] = useState<string | null>(null);
|
||||
const [supplyIsStale, setSupplyIsStale] = useState(false);
|
||||
const [trends, setTrends] = useState<DouyuPlatformTrends | null>(null);
|
||||
const [trendAlerts, setTrendAlerts] = useState<DouyuPlatformAlert[]>([]);
|
||||
const [statusLoading, setStatusLoading] = useState(false);
|
||||
@@ -209,6 +211,8 @@ export default function AccountPlatformStatusPanel() {
|
||||
const response = await douyuApi.getAccountPlatformSupply();
|
||||
setSupplyTargets(response.supply_targets);
|
||||
setSupplyAlerts(response.alerts);
|
||||
setSupplyCheckedAt(response.checked_at ?? null);
|
||||
setSupplyIsStale(Boolean(response.is_stale));
|
||||
} catch (loadError: unknown) {
|
||||
setSupplyAlerts([{
|
||||
code: 'account_supply_load_failed',
|
||||
@@ -691,7 +695,15 @@ export default function AccountPlatformStatusPanel() {
|
||||
/>
|
||||
|
||||
<Space orientation="vertical" size={2} style={{ width: '100%', marginTop: 20 }}>
|
||||
<Text strong>账号供给目标</Text>
|
||||
<Space size={8} wrap>
|
||||
<Text strong>账号供给目标</Text>
|
||||
{supplyCheckedAt ? (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
快照时间:{formatTime(supplyCheckedAt)}
|
||||
</Text>
|
||||
) : null}
|
||||
{supplyIsStale ? <Tag color="warning">快照已陈旧</Tag> : null}
|
||||
</Space>
|
||||
<Text type="secondary">按高价值、普通账号和商品维度维护可兑换与可分配库存</Text>
|
||||
</Space>
|
||||
<Table
|
||||
|
||||
Reference in New Issue
Block a user