feat(automation): 持久执行队列与重复充值确认
This commit is contained in:
@@ -23,6 +23,14 @@ def test_background_services_start_and_stop_once(monkeypatch):
|
||||
"web.backend.services.automation.stop_scheduler",
|
||||
mark("stop-scheduler"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.execution_worker.start_execution_job_worker",
|
||||
mark("execution"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.execution_worker.stop_execution_job_worker",
|
||||
mark("stop-execution"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.platform_fulfillment.reconciler."
|
||||
"start_platform_fulfillment_reconciler",
|
||||
@@ -78,6 +86,7 @@ def test_background_services_start_and_stop_once(monkeypatch):
|
||||
background_runtime.stop_background_services()
|
||||
|
||||
assert calls == [
|
||||
"execution",
|
||||
"register",
|
||||
"scheduler",
|
||||
"outbox",
|
||||
@@ -91,4 +100,27 @@ def test_background_services_start_and_stop_once(monkeypatch):
|
||||
"stop-reconciler",
|
||||
"stop-outbox",
|
||||
"stop-scheduler",
|
||||
"stop-execution",
|
||||
]
|
||||
|
||||
|
||||
def test_execution_only_worker_can_disable_control_plane(monkeypatch):
|
||||
calls: list[str] = []
|
||||
monkeypatch.setenv("BACKGROUND_CONTROL_PLANE_ENABLED", "false")
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.execution_worker.start_execution_job_worker",
|
||||
lambda: calls.append("start") or True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.execution_worker.stop_execution_job_worker",
|
||||
lambda: calls.append("stop"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.automation.start_scheduler",
|
||||
lambda: (_ for _ in ()).throw(AssertionError("control plane must stay off")),
|
||||
)
|
||||
|
||||
assert background_runtime.start_background_services() is True
|
||||
background_runtime.stop_background_services()
|
||||
|
||||
assert calls == ["start", "stop"]
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""斗鱼 API 直充重复请求确认测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
DouyuRechargeConfirmation,
|
||||
DouyuTask,
|
||||
ExecutionJob,
|
||||
User,
|
||||
)
|
||||
from web.backend.routers import douyu as douyu_router
|
||||
from web.backend.schemas import DouyuTaskBatchRequest
|
||||
from web.backend.services.douyu_service import ensure_douyu_config
|
||||
|
||||
|
||||
def _fixture(db):
|
||||
user = User(
|
||||
username="recharge-guard-user",
|
||||
password_hash="h",
|
||||
role="super_admin",
|
||||
is_active=True,
|
||||
)
|
||||
account = Account(
|
||||
username="recharge-guard-account",
|
||||
password="p",
|
||||
email="guard@example.com",
|
||||
email_password="ep",
|
||||
cookie="acf_uid=1; acf_auth=x",
|
||||
ck_check_status="valid",
|
||||
auto_managed=True,
|
||||
)
|
||||
db.add_all([user, account])
|
||||
db.commit()
|
||||
config = ensure_douyu_config(db)
|
||||
config.gold_recharge_channel = "supplier_api"
|
||||
config.recharge_duplicate_confirm_minutes = 10
|
||||
db.commit()
|
||||
return user, account
|
||||
|
||||
|
||||
def _request(account: Account, *, token: str | None = None) -> DouyuTaskBatchRequest:
|
||||
return DouyuTaskBatchRequest(
|
||||
account_ids=[int(account.id)],
|
||||
task_type="create_gold_qr",
|
||||
handbook_scope="elite",
|
||||
concurrency=1,
|
||||
payload={"amount": 30},
|
||||
recharge_confirmation_token=token,
|
||||
)
|
||||
|
||||
|
||||
def test_second_api_recharge_requires_one_time_confirmation(db):
|
||||
user, account = _fixture(db)
|
||||
|
||||
first = douyu_router._prepare_task_batch(_request(account), db, user)
|
||||
assert first["success"] is True
|
||||
assert first["count"] == 1
|
||||
|
||||
db.query(DouyuTask).update(
|
||||
{
|
||||
DouyuTask.status: "success",
|
||||
DouyuTask.message: "上一笔已完成",
|
||||
},
|
||||
synchronize_session=False,
|
||||
)
|
||||
db.commit()
|
||||
second = douyu_router._prepare_task_batch(_request(account), db, user)
|
||||
assert second["requires_confirmation"] is True
|
||||
assert second["confirmation_token"]
|
||||
assert db.query(DouyuTask).count() == 1
|
||||
|
||||
confirmed = douyu_router._prepare_task_batch(
|
||||
_request(account, token=second["confirmation_token"]),
|
||||
db,
|
||||
user,
|
||||
)
|
||||
assert confirmed["success"] is True
|
||||
assert db.query(DouyuTask).count() == 2
|
||||
confirmation = db.query(DouyuRechargeConfirmation).one()
|
||||
assert confirmation.used_at is not None
|
||||
|
||||
replay = _request(account, token=second["confirmation_token"])
|
||||
try:
|
||||
douyu_router._prepare_task_batch(replay, db, user)
|
||||
except HTTPException as exc:
|
||||
assert exc.status_code == 409
|
||||
else:
|
||||
raise AssertionError("confirmation token must be one-time")
|
||||
|
||||
|
||||
def test_qr_recharge_and_zero_window_do_not_require_confirmation(db):
|
||||
user, account = _fixture(db)
|
||||
config = ensure_douyu_config(db)
|
||||
config.gold_recharge_channel = "wechat_qr"
|
||||
db.commit()
|
||||
|
||||
douyu_router._prepare_task_batch(_request(account), db, user)
|
||||
db.query(DouyuTask).update(
|
||||
{DouyuTask.status: "success"},
|
||||
synchronize_session=False,
|
||||
)
|
||||
db.commit()
|
||||
douyu_router._prepare_task_batch(_request(account), db, user)
|
||||
assert db.query(DouyuTask).count() == 2
|
||||
|
||||
config.gold_recharge_channel = "supplier_api"
|
||||
config.recharge_duplicate_confirm_minutes = 0
|
||||
db.query(DouyuTask).update(
|
||||
{DouyuTask.status: "success"},
|
||||
synchronize_session=False,
|
||||
)
|
||||
db.commit()
|
||||
result = douyu_router._prepare_task_batch(_request(account), db, user)
|
||||
assert result["success"] is True
|
||||
assert db.query(ExecutionJob).count() == 3
|
||||
@@ -10,6 +10,7 @@ from tests.support.db import init_test_schema, make_test_session
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
DouyuTask,
|
||||
ExecutionJob,
|
||||
PlatformFulfillmentEvent,
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
@@ -262,12 +263,6 @@ def test_platform_exchange_checks_eligibility_before_creating_task(monkeypatch):
|
||||
"refresh_exchange_eligibility",
|
||||
fake_refresh,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
douyu_router,
|
||||
"start_douyu_batch",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
result = asyncio.run(
|
||||
douyu_router.create_task_batch(
|
||||
DouyuTaskBatchRequest(
|
||||
@@ -287,6 +282,12 @@ def test_platform_exchange_checks_eligibility_before_creating_task(monkeypatch):
|
||||
assert result["count"] == 1
|
||||
created = db.query(DouyuTask).filter(DouyuTask.batch_id == result["batch_id"]).one()
|
||||
assert created.platform_task_id == task.id
|
||||
job = (
|
||||
db.query(ExecutionJob)
|
||||
.filter(ExecutionJob.batch_id == result["batch_id"])
|
||||
.one()
|
||||
)
|
||||
assert job.status == "queued"
|
||||
event = (
|
||||
db.query(PlatformFulfillmentEvent)
|
||||
.filter(
|
||||
|
||||
@@ -13,7 +13,14 @@ from datetime import UTC, datetime, timedelta
|
||||
from sqlalchemy import func
|
||||
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import Account, AutomationJob, DouyuTask, User
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AutomationJob,
|
||||
DouyuTask,
|
||||
ExecutionJob,
|
||||
ExecutionJobEvent,
|
||||
User,
|
||||
)
|
||||
from web.backend.services.automation.jobs import douyu_tasks_retention as retention
|
||||
|
||||
NOW = datetime.now(UTC)
|
||||
@@ -215,6 +222,36 @@ class TestRetention(_Base):
|
||||
out = self.run(noise_days=7, business_days=90, max_batches=50)
|
||||
assert out["batch_budget_exhausted"] is False
|
||||
|
||||
def test_old_execution_jobs_and_events_are_cleaned(self):
|
||||
job = ExecutionJob(
|
||||
job_type="login_batch",
|
||||
lane_scope="auth",
|
||||
batch_id="old-execution-batch",
|
||||
status="succeeded",
|
||||
available_at=NOW - timedelta(days=100),
|
||||
created_by=self.user_id,
|
||||
finished_at=NOW - timedelta(days=100),
|
||||
created_at=NOW - timedelta(days=100),
|
||||
)
|
||||
self.session.add(job)
|
||||
self.session.flush()
|
||||
self.session.add(
|
||||
ExecutionJobEvent(
|
||||
job_id=job.id,
|
||||
batch_id=job.batch_id,
|
||||
level="result",
|
||||
message="done",
|
||||
created_at=NOW - timedelta(days=100),
|
||||
)
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
out = self.run(noise_days=7, business_days=90)
|
||||
|
||||
assert out["deleted_execution_events"] == 1
|
||||
assert out["deleted_execution_jobs"] == 1
|
||||
assert self.session.query(ExecutionJob).count() == 0
|
||||
|
||||
|
||||
class TestClassification(_Base):
|
||||
def test_noise_list_has_no_duplicates(self):
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""持久批次执行任务租约、取消和事件测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from web.backend.models import ExecutionJob, User
|
||||
from web.backend.services import execution_worker
|
||||
from web.backend.services.execution_jobs import (
|
||||
JOB_LOGIN_BATCH,
|
||||
LANE_AUTH,
|
||||
STATUS_CANCELLED,
|
||||
STATUS_RUNNING,
|
||||
claim_execution_jobs,
|
||||
enqueue_execution_job,
|
||||
finish_execution_job,
|
||||
heartbeat_execution_job,
|
||||
request_execution_cancel,
|
||||
)
|
||||
|
||||
|
||||
def _user(db, name: str = "execution-user") -> User:
|
||||
user = User(
|
||||
username=name,
|
||||
password_hash="h",
|
||||
role="super_admin",
|
||||
is_active=True,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_job_claim_heartbeat_cancel_and_finish(db):
|
||||
user = _user(db)
|
||||
job = enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_LOGIN_BATCH,
|
||||
lane_scope=LANE_AUTH,
|
||||
batch_id="exec-claim",
|
||||
payload={"account_ids": [1]},
|
||||
created_by=int(user.id),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
claimed = claim_execution_jobs(
|
||||
lane_scopes=(LANE_AUTH,),
|
||||
owner="worker-a",
|
||||
limit=1,
|
||||
)
|
||||
assert [row.id for row in claimed] == [job.id]
|
||||
assert claimed[0].status == STATUS_RUNNING
|
||||
assert claimed[0].attempt_count == 1
|
||||
|
||||
held, cancel_requested = heartbeat_execution_job(
|
||||
job_id=int(job.id),
|
||||
owner="worker-a",
|
||||
)
|
||||
assert held is True
|
||||
assert cancel_requested is False
|
||||
|
||||
request_execution_cancel(db, batch_id="exec-claim")
|
||||
db.commit()
|
||||
held, cancel_requested = heartbeat_execution_job(
|
||||
job_id=int(job.id),
|
||||
owner="worker-a",
|
||||
)
|
||||
assert held is True
|
||||
assert cancel_requested is True
|
||||
assert finish_execution_job(
|
||||
job_id=int(job.id),
|
||||
owner="worker-a",
|
||||
status=STATUS_CANCELLED,
|
||||
)
|
||||
|
||||
|
||||
def test_queued_job_cancel_is_immediate_and_token_scoped(db):
|
||||
user = _user(db, "execution-cancel")
|
||||
job = enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_LOGIN_BATCH,
|
||||
lane_scope=LANE_AUTH,
|
||||
batch_id="exec-cancel",
|
||||
payload={},
|
||||
created_by=int(user.id),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
request_execution_cancel(db, batch_id=job.batch_id)
|
||||
db.commit()
|
||||
db.refresh(job)
|
||||
|
||||
assert job.status == STATUS_CANCELLED
|
||||
assert job.cancel_requested_at is not None
|
||||
|
||||
|
||||
def test_expired_running_job_is_recovered(db):
|
||||
user = _user(db, "execution-recover")
|
||||
job = enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_LOGIN_BATCH,
|
||||
lane_scope=LANE_AUTH,
|
||||
batch_id="exec-recover",
|
||||
payload={},
|
||||
created_by=int(user.id),
|
||||
)
|
||||
job.status = STATUS_RUNNING
|
||||
job.lease_owner = "dead-worker"
|
||||
job.lease_expires_at = datetime.now(UTC) - timedelta(minutes=1)
|
||||
job.attempt_count = 1
|
||||
job.max_attempts = 2
|
||||
db.commit()
|
||||
|
||||
claimed = claim_execution_jobs(
|
||||
lane_scopes=(LANE_AUTH,),
|
||||
owner="worker-b",
|
||||
limit=1,
|
||||
)
|
||||
|
||||
assert len(claimed) == 1
|
||||
assert claimed[0].lease_owner == "worker-b"
|
||||
assert claimed[0].attempt_count == 2
|
||||
|
||||
|
||||
def test_execution_worker_runs_claimed_login_batch(db, monkeypatch):
|
||||
user = _user(db, "execution-run")
|
||||
job = enqueue_execution_job(
|
||||
db,
|
||||
job_type=JOB_LOGIN_BATCH,
|
||||
lane_scope=LANE_AUTH,
|
||||
batch_id="exec-run",
|
||||
payload={
|
||||
"account_ids": [1],
|
||||
"mode": "login",
|
||||
"concurrency": 1,
|
||||
},
|
||||
created_by=int(user.id),
|
||||
)
|
||||
db.commit()
|
||||
worker = execution_worker.ExecutionJobWorker()
|
||||
claimed = claim_execution_jobs(
|
||||
lane_scopes=(LANE_AUTH,),
|
||||
owner=worker._owner,
|
||||
limit=1,
|
||||
)
|
||||
assert [row.id for row in claimed] == [job.id]
|
||||
seen: dict = {}
|
||||
|
||||
class FakeLoginRunner:
|
||||
def __init__(self, **kwargs):
|
||||
seen.update(kwargs)
|
||||
|
||||
def run(self):
|
||||
seen["ran"] = True
|
||||
|
||||
monkeypatch.setattr(execution_worker, "LoginBatchRunner", FakeLoginRunner)
|
||||
worker._run_job(int(job.id))
|
||||
assert seen.get("ran") is True
|
||||
|
||||
db.rollback()
|
||||
db.expire_all()
|
||||
refreshed = db.get(ExecutionJob, job.id)
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == "succeeded"
|
||||
assert seen["ran"] is True
|
||||
assert seen["batch_id"] == "exec-run"
|
||||
@@ -15,10 +15,19 @@ def test_login_runner_reserves_quota_before_attempt() -> None:
|
||||
assert "reserve_login_attempt(" in source
|
||||
|
||||
|
||||
def test_known_login_entrypoints_construct_login_runner() -> None:
|
||||
def test_manual_login_entrypoints_enqueue_durable_worker_job() -> None:
|
||||
for relative in (
|
||||
"web/backend/routers/login.py",
|
||||
"web/backend/routers/cookies.py",
|
||||
):
|
||||
source = (ROOT / relative).read_text(encoding="utf-8")
|
||||
assert "enqueue_execution_job(" in source, relative
|
||||
assert "LoginBatchRunner(" not in source, relative
|
||||
|
||||
|
||||
def test_background_entrypoints_construct_login_runner() -> None:
|
||||
for relative in (
|
||||
"web/backend/services/execution_worker.py",
|
||||
"web/backend/services/automation/jobs/ck_relogin.py",
|
||||
):
|
||||
source = (ROOT / relative).read_text(encoding="utf-8")
|
||||
|
||||
@@ -9,7 +9,7 @@ import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import Account, LoginTask, User
|
||||
from web.backend.models import Account, ExecutionJob, LoginTask, User
|
||||
from web.backend.routers.login import (
|
||||
create_batch,
|
||||
delete_tasks,
|
||||
@@ -208,3 +208,24 @@ class TestLoginTaskFilters:
|
||||
)
|
||||
assert f"当前选择了 {requested} 个" in str(exc_info.value.detail)
|
||||
assert "请分批操作" in str(exc_info.value.detail)
|
||||
|
||||
def test_batch_login_enqueues_durable_execution_job(self):
|
||||
result = asyncio.run(
|
||||
create_batch(
|
||||
LoginBatchRequest(
|
||||
account_ids=[int(self.account_a.id)],
|
||||
mode="login",
|
||||
),
|
||||
db=self.db,
|
||||
current=self.admin,
|
||||
)
|
||||
)
|
||||
|
||||
job = (
|
||||
self.db.query(ExecutionJob)
|
||||
.filter(ExecutionJob.batch_id == result["batch_id"])
|
||||
.one()
|
||||
)
|
||||
assert job.job_type == "login_batch"
|
||||
assert job.lane_scope == "auth"
|
||||
assert job.status == "queued"
|
||||
|
||||
@@ -42,7 +42,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261123_0121"
|
||||
HEAD_REVISION = "20261123_0122"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
|
||||
@@ -1755,8 +1755,8 @@ class TestBindingAndCompletion(_Base):
|
||||
self.session.commit()
|
||||
monkeypatch.setattr(
|
||||
service.binding,
|
||||
"start_douyu_batch",
|
||||
lambda **_kwargs: None,
|
||||
"enqueue_execution_job",
|
||||
lambda _db, **_kwargs: None,
|
||||
)
|
||||
|
||||
asyncio.run(
|
||||
@@ -1822,8 +1822,8 @@ class TestBindingAndCompletion(_Base):
|
||||
task = self._allocated()
|
||||
monkeypatch.setattr(
|
||||
service.binding,
|
||||
"start_douyu_batch",
|
||||
lambda **_kwargs: None,
|
||||
"enqueue_execution_job",
|
||||
lambda _db, **_kwargs: None,
|
||||
)
|
||||
|
||||
first = asyncio.run(service.customer_start_binding(self.session, task_id=task.id))
|
||||
@@ -1848,21 +1848,21 @@ class TestBindingAndCompletion(_Base):
|
||||
captured: dict[str, object] = {}
|
||||
monkeypatch.setattr(
|
||||
service.binding,
|
||||
"start_douyu_batch",
|
||||
lambda **kwargs: captured.update(kwargs),
|
||||
"enqueue_execution_job",
|
||||
lambda _db, **kwargs: captured.update(kwargs),
|
||||
)
|
||||
|
||||
asyncio.run(service.customer_start_binding(self.session, task_id=task.id))
|
||||
|
||||
assert captured["capture_event_loop"] is False
|
||||
assert "loop" not in captured
|
||||
assert captured["job_type"] == "douyu_binding"
|
||||
assert captured["batch_id"].startswith(f"pfbind-{task.id}-")
|
||||
|
||||
def test_concurrent_start_binding_creates_one_task(self, monkeypatch):
|
||||
task = self._allocated()
|
||||
monkeypatch.setattr(
|
||||
service.binding,
|
||||
"start_douyu_batch",
|
||||
lambda **_kwargs: None,
|
||||
"enqueue_execution_job",
|
||||
lambda _db, **_kwargs: None,
|
||||
)
|
||||
barrier = threading.Barrier(2)
|
||||
errors: list[BaseException] = []
|
||||
@@ -1936,8 +1936,8 @@ class TestBindingAndCompletion(_Base):
|
||||
self.session.commit()
|
||||
monkeypatch.setattr(
|
||||
service.binding,
|
||||
"start_douyu_batch",
|
||||
lambda **_kwargs: None,
|
||||
"enqueue_execution_job",
|
||||
lambda _db, **_kwargs: None,
|
||||
)
|
||||
|
||||
asyncio.run(
|
||||
@@ -2457,8 +2457,8 @@ class TestBindingAndCompletion(_Base):
|
||||
self.session.commit()
|
||||
monkeypatch.setattr(
|
||||
service.binding,
|
||||
"start_douyu_batch",
|
||||
lambda **_kwargs: None,
|
||||
"enqueue_execution_job",
|
||||
lambda _db, **_kwargs: None,
|
||||
)
|
||||
|
||||
asyncio.run(
|
||||
|
||||
Reference in New Issue
Block a user