fix(douyu): unify binding state and scheduler health

This commit is contained in:
yml
2026-11-23 20:16:59 +08:00
parent 0a32f24fa8
commit e6629a9c91
20 changed files with 1336 additions and 158 deletions
+44 -1
View File
@@ -537,7 +537,15 @@ class TestAutomationApi(_Base):
return api
def test_list_jobs_exposes_scheduler_and_job_state(self):
def test_list_jobs_exposes_scheduler_and_job_state(
self,
monkeypatch,
tmp_path,
):
monkeypatch.setenv(
"BACKGROUND_RUNTIME_HEARTBEAT_PATH",
str(tmp_path / "background_runtime.json"),
)
api = self._api()
payload = api.list_jobs(db=self.session, current=self.admin)
# 心跳(轮询间隔)与作业周期是两个概念,接口都要暴露出来:
@@ -557,6 +565,41 @@ class TestAutomationApi(_Base):
assert job["batch_size"] == 200
assert job["latest_run"] is None
def test_list_jobs_uses_background_process_scheduler_heartbeat(
self,
monkeypatch,
):
api = self._api()
monkeypatch.setattr(
api,
"scheduler_status",
lambda: {
"enabled": True,
"running": False,
"tick_seconds": 5,
"job_interval_seconds": 300,
"registered": [],
},
)
monkeypatch.setattr(
"web.backend.background_runtime.background_runtime_status",
lambda: {
"running": True,
"heartbeatAt": "2026-11-23T12:00:00+00:00",
"ageSeconds": 3.0,
"staleAfterSeconds": 30,
"pid": 123,
"scheduler": {"enabled": True, "running": True},
},
)
payload = api.list_jobs(db=self.session, current=self.admin)
assert payload["scheduler"]["running"] is True
assert payload["scheduler"]["process"] == "background"
assert payload["scheduler"]["pid"] == 123
assert payload["runtime"]["background_runtime"]["ageSeconds"] == 3.0
def test_update_job_persists_and_schedules_next_run(self):
api = self._api()
api.update_job(
+39 -2
View File
@@ -2,11 +2,16 @@
from __future__ import annotations
import json
from pathlib import Path
from web.backend import background_runtime
def test_background_services_start_and_stop_once(monkeypatch):
def test_background_services_start_and_stop_once(monkeypatch, tmp_path):
calls: list[str] = []
heartbeat_path = tmp_path / "background_runtime.json"
monkeypatch.setenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", str(heartbeat_path))
def mark(name: str):
return lambda *_args, **_kwargs: calls.append(name) or True
@@ -84,6 +89,7 @@ def test_background_services_start_and_stop_once(monkeypatch):
assert background_runtime.start_background_services() is False
background_runtime.stop_background_services()
background_runtime.stop_background_services()
assert not heartbeat_path.exists()
assert calls == [
"execution",
@@ -104,9 +110,13 @@ def test_background_services_start_and_stop_once(monkeypatch):
]
def test_execution_only_worker_can_disable_control_plane(monkeypatch):
def test_execution_only_worker_can_disable_control_plane(monkeypatch, tmp_path):
calls: list[str] = []
monkeypatch.setenv("BACKGROUND_CONTROL_PLANE_ENABLED", "false")
monkeypatch.setenv(
"BACKGROUND_RUNTIME_HEARTBEAT_PATH",
str(tmp_path / "background_runtime.json"),
)
monkeypatch.setattr(
"web.backend.services.execution_worker.start_execution_job_worker",
lambda: calls.append("start") or True,
@@ -124,3 +134,30 @@ def test_execution_only_worker_can_disable_control_plane(monkeypatch):
background_runtime.stop_background_services()
assert calls == ["start", "stop"]
def test_background_runtime_heartbeat_reports_scheduler_process(
monkeypatch,
tmp_path,
):
heartbeat_path = tmp_path / "background_runtime.json"
monkeypatch.setenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", str(heartbeat_path))
monkeypatch.setattr(
"web.backend.services.automation.scheduler.scheduler_status",
lambda: {
"enabled": True,
"running": True,
"tick_seconds": 5,
"job_interval_seconds": 300,
"registered": ["ck_relogin"],
},
)
background_runtime._write_runtime_heartbeat()
status = background_runtime.background_runtime_status()
payload = json.loads(Path(heartbeat_path).read_text(encoding="utf-8"))
assert status["running"] is True
assert status["pid"] == payload["pid"]
assert status["scheduler"]["running"] is True
assert status["ageSeconds"] is not None
+126 -1
View File
@@ -8,7 +8,7 @@ from typing import Any
import pytest
from core.douyu import DouyuActivityClient, DouyuActivityError
from web.backend.models import Account
from web.backend.models import Account, DouyuTask
from web.backend.services.account_binding import (
BIND_BOUND,
BIND_PENDING,
@@ -24,6 +24,13 @@ from web.backend.services.account_binding import (
pending_binding_role_from_result,
role_change_available_at,
)
from web.backend.services.douyu_binding import (
BINDING_VIEW_CONFIRMED,
BINDING_VIEW_FAILED,
BINDING_VIEW_NONE,
BINDING_VIEW_PENDING,
resolve_douyu_binding,
)
from web.backend.services.douyu_runner_bind import BindMixin
ACT_ALIAS = "20260120QYOOB"
@@ -362,6 +369,124 @@ def test_task_result_helpers_accept_existing_action_alias_pending():
assert binding_role_from_result(result) == "只为爱杰宝"
def _binding_task(*, status: str, result: dict[str, Any]) -> DouyuTask:
return DouyuTask(
id=101,
batch_id="binding-view",
account_id=1,
created_by=1,
task_type="get_bind_qr",
handbook_scope="elite",
status=status,
result=result,
)
def _binding_account() -> Account:
return Account(
username="binding-view",
password="p",
email="binding-view@example.com",
email_password="ep",
status="active",
game_name="当前生效角色",
game_channel="微信 · 苹果(iOS)",
role_bind_status=BIND_BOUND,
)
def test_binding_view_keeps_pending_role_separate_from_account_binding():
task = _binding_task(
status="success",
result={
"role_name": "本次待确认角色",
"area_name": "手Q",
"plat_name": "苹果(iOS)",
"baseline_role_name": "当前生效角色",
"before_bind_info": {
"act_alias": ACT_ALIAS,
"role_name": "当前生效角色",
"is_bound_act": True,
"need_bind_act": True,
},
"act_alias": ACT_ALIAS,
"need_bind_act": True,
"is_bound_act": False,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
)
account = _binding_account()
binding = resolve_douyu_binding(task, account=account)
assert binding.status == BINDING_VIEW_PENDING
assert binding.pending_role_name == "本次待确认角色"
assert binding.pending_channel == "手Q / 苹果(iOS)"
assert binding.current_role_name == "当前生效角色"
assert binding.current_channel == "微信 · 苹果(iOS)"
assert binding.effective_role_name == "本次待确认角色"
assert binding.bind_confirmed is False
assert binding.bind_ready_for_confirm is True
assert binding.account_bind_status == BIND_BOUND
def test_binding_view_confirms_only_from_confirmation_task_result():
task = _binding_task(
status="success",
result={
"role_name": "本次已确认角色",
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_act": True,
"bind_confirmed": True,
"bind_phase": "confirmed",
},
)
task.task_type = "confirm_bind"
account = _binding_account()
binding = resolve_douyu_binding(task, account=account)
assert binding.status == BINDING_VIEW_CONFIRMED
assert binding.confirmed_role_name == "本次已确认角色"
assert binding.confirmed_channel == "微信 / 安卓(android)"
assert binding.current_role_name == "当前生效角色"
assert binding.effective_role_name == "本次已确认角色"
assert binding.bind_confirmed is True
assert binding.bind_ready_for_confirm is False
def test_binding_view_failure_never_becomes_confirmed():
task = _binding_task(
status="failed",
result={
"role_name": "未生效角色",
"bind_ready_for_confirm": True,
"bind_confirmed": True,
"bind_phase": "confirm_failed",
},
)
binding = resolve_douyu_binding(task, account=_binding_account())
assert binding.status == BINDING_VIEW_FAILED
assert binding.bind_confirmed is False
assert binding.bind_ready_for_confirm is False
def test_account_binding_without_task_does_not_confirm_fulfillment_order():
account = _binding_account()
binding = resolve_douyu_binding(None, account=account)
assert binding.status == BINDING_VIEW_NONE
assert binding.current_role_name == "当前生效角色"
assert binding.account_bind_status == BIND_BOUND
assert binding.bind_confirmed is False
def test_confirmed_new_role_replaces_account_current_role():
account = Account(
username="replace-role",
+145 -1
View File
@@ -44,7 +44,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261123_0126"
HEAD_REVISION = "20261123_0127"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -582,6 +582,150 @@ class TestMigrationSmoke:
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
def test_0127_links_latest_pending_account_workbench_role(self):
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
mig_url = (
f"mysql+pymysql://{quote_plus(creds['user'])}:"
f"{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/"
f"{mig_db}?charset=utf8mb4"
)
admin_engine = get_test_engine()
mig_engine = create_engine(mig_url)
original_url = database_module.DATABASE_URL
with admin_engine.begin() as conn:
conn.execute(
text(
f"CREATE DATABASE `{mig_db}` "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
)
)
try:
database_module.DATABASE_URL = mig_url
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0126")
with Session(mig_engine) as session:
user = User(
username="pending-link-user",
password_hash="hash",
role="super_admin",
is_active=True,
)
account = Account(
username="pending-link-account",
password="password",
email="pending-link@example.com",
email_password="mail-password",
cookie="acf_uid=1",
role_bind_status="bound",
game_name="历史角色",
status="active",
)
session.add_all([user, account])
session.flush()
lease = AccountLease(
account_id=account.id,
holder_user_id=user.id,
status="active",
purpose="platform_fulfillment",
)
old_bind_task = DouyuTask(
batch_id="pending-link-old",
account_id=account.id,
account_assigned_to=user.id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={"role_name": "旧待确认角色"},
created_by=user.id,
)
latest_bind_task = DouyuTask(
batch_id="pending-link-latest",
account_id=account.id,
account_assigned_to=user.id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "最新待确认角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"act_alias": "20260120QYOOB",
"need_bind_act": True,
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=user.id,
)
session.add_all([lease, old_bind_task, latest_bind_task])
session.flush()
stale_bind_task = DouyuTask(
batch_id="pending-link-stale",
account_id=account.id,
account_assigned_to=user.id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "历史角色",
"baseline_role_name": "历史角色",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=user.id,
)
session.add(stale_bind_task)
session.flush()
task = PlatformFulfillmentTask(
source_system="order_site",
source_order_id="PENDING-LINK-ORDER",
source_order_item_id="PENDING-LINK-ITEM",
platform_order_id="PENDING-LINK-PLATFORM",
internal_sku_key="待确认角色回接",
sku_name="待确认角色回接",
scope="elite",
account_id=account.id,
lease_id=lease.id,
bind_task_id=old_bind_task.id,
binding_status="role_ready",
execution_status="role_ready",
)
session.add(task)
session.commit()
task_id = int(task.id)
latest_bind_task_id = int(latest_bind_task.id)
old_bind_task_id = int(old_bind_task.id)
command.upgrade(cfg, "head")
with Session(mig_engine) as session:
task = session.get(PlatformFulfillmentTask, task_id)
event = (
session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task_id,
event_type="binding_pending_task_linked",
)
.one()
)
assert task.bind_task_id == latest_bind_task_id
assert task.binding_status == "role_ready"
assert event.detail_json["previousBindTaskId"] == old_bind_task_id
assert event.detail_json["roleName"] == "最新待确认角色"
finally:
database_module.DATABASE_URL = original_url
mig_engine.dispose()
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))
def test_0125_preserves_shop_names_without_automatic_aliases(self):
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
+171
View File
@@ -1889,6 +1889,50 @@ class TestBindingAndCompletion(_Base):
assert task.bind_task_id == confirm_task.id
assert event.detail_json["roleName"] == "新角色"
def test_account_bound_does_not_confirm_unconfirmed_confirmation_task(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
account.role_bind_status = "bound"
account.game_name = "账号当前角色"
task.binding_status = "role_ready"
task.execution_status = "role_ready"
confirm_task = DouyuTask(
batch_id="unconfirmed-confirm-task",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="success",
result={
"role_name": "账号当前角色",
"is_bound_act": True,
"bind_confirmed": False,
"bind_phase": "waiting_role",
},
created_by=self.admin_id,
)
self.session.add(confirm_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=confirm_task.id,
)
self.session.refresh(task)
assert synced == 0
assert task.binding_status == "role_ready"
assert task.execution_status == "role_ready"
assert (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_synced_from_account",
)
.count()
== 0
)
def test_bind_qr_success_does_not_promote_existing_account_binding(self):
task = self._allocated()
account = self.session.get(Account, task.account_id)
@@ -1954,6 +1998,133 @@ class TestBindingAndCompletion(_Base):
== 0
)
def test_standalone_pending_bind_task_links_to_active_fulfillment_task(self):
task = self._allocated()
old_bind_task = DouyuTask(
batch_id="bind-old-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "旧待确认角色",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(old_bind_task)
self.session.flush()
task.bind_task_id = old_bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
latest_bind_task = DouyuTask(
batch_id="account-workbench-new-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "最新待确认角色",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add(latest_bind_task)
self.session.commit()
synced = service.sync_task_from_binding_runner(
self.session,
douyu_task_id=latest_bind_task.id,
)
self.session.refresh(task)
detail = service.get_task_detail(self.session, task.id)
assert synced == 1
assert task.bind_task_id == latest_bind_task.id
assert task.binding_status == "role_ready"
assert detail["task"]["bindTask"]["roleName"] == "最新待确认角色"
event = (
self.session.query(PlatformFulfillmentEvent)
.filter_by(
task_id=task.id,
event_type="binding_pending_task_linked",
)
.one()
)
assert event.detail_json["previousBindTaskId"] == old_bind_task.id
assert event.detail_json["bindTaskId"] == latest_bind_task.id
def test_refresh_binding_attaches_latest_pending_account_workbench_role(self):
task = self._allocated()
old_bind_task = DouyuTask(
batch_id="refresh-old-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={"role_name": "旧待确认角色", "bind_ready_for_confirm": True},
created_by=self.admin_id,
)
latest_bind_task = DouyuTask(
batch_id="refresh-latest-pending",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="get_bind_qr",
handbook_scope="elite",
status="success",
result={
"role_name": "最新待确认角色",
"current_role_name": "历史角色",
"baseline_role_name": "历史角色",
"before_bind_info": {
"act_alias": "20260120QYOOB",
"role_name": "历史角色",
"is_bound_act": True,
"need_bind_act": True,
},
"bind_ready_for_confirm": True,
"bind_confirmed": False,
"bind_phase": "role_ready",
},
created_by=self.admin_id,
)
self.session.add_all([old_bind_task, latest_bind_task])
self.session.flush()
task.bind_task_id = old_bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
self.session.refresh(task)
assert task.bind_task_id == latest_bind_task.id
assert detail["task"]["bindTask"]["roleName"] == "最新待确认角色"
assert detail["task"]["bindTask"]["bindReadyForConfirm"] is True
def test_customer_start_mapping_missing_is_idempotent(self, monkeypatch):
task = self.task(mapped=False)
task.issue_code = "mapping_missing"