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
@@ -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)]