From aaacbea10af84bb816f4c6649c6fbbad3a4d6e93 Mon Sep 17 00:00:00 2001 From: yml Date: Mon, 23 Nov 2026 15:47:56 +0800 Subject: [PATCH] =?UTF-8?q?feat(automation):=20=E6=8C=81=E4=B9=85=E6=89=A7?= =?UTF-8?q?=E8=A1=8C=E9=98=9F=E5=88=97=E4=B8=8E=E9=87=8D=E5=A4=8D=E5=85=85?= =?UTF-8?q?=E5=80=BC=E7=A1=AE=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 6 + docker-compose.yml | 5 + tests/test_background_runtime.py | 32 ++ tests/test_douyu_recharge_guard.py | 118 ++++++ .../test_douyu_task_assigned_optimization.py | 13 +- tests/test_douyu_tasks_retention.py | 39 +- tests/test_execution_jobs.py | 166 ++++++++ tests/test_login_entrypoint_audit.py | 11 +- tests/test_login_task_filters.py | 23 +- tests/test_migrations.py | 2 +- tests/test_platform_fulfillment.py | 28 +- web/backend/background_runtime.py | 53 ++- .../migrations/migration_manifest.json | 4 + ...1123_0122_execution_jobs_recharge_guard.py | 231 ++++++++++ web/backend/models.py | 124 ++++++ web/backend/routers/automation.py | 2 + web/backend/routers/cookies.py | 92 ++-- web/backend/routers/douyu.py | 297 +++++++++++-- web/backend/routers/login.py | 144 +++++-- web/backend/schemas.py | 6 + .../automation/jobs/douyu_tasks_retention.py | 51 ++- web/backend/services/douyu_runner_core.py | 23 +- web/backend/services/douyu_service.py | 34 +- web/backend/services/execution_jobs.py | 394 ++++++++++++++++++ web/backend/services/execution_worker.py | 312 ++++++++++++++ web/backend/services/login_service.py | 15 +- .../services/platform_fulfillment/binding.py | 44 +- web/frontend/src/api/types.ts | 8 + .../src/pages/douyu-tasks/DouyuTasksPage.tsx | 48 +++ 29 files changed, 2147 insertions(+), 178 deletions(-) create mode 100644 tests/test_douyu_recharge_guard.py create mode 100644 tests/test_execution_jobs.py create mode 100644 web/backend/migrations/versions/20261123_0122_execution_jobs_recharge_guard.py create mode 100644 web/backend/services/execution_jobs.py create mode 100644 web/backend/services/execution_worker.py diff --git a/.env.example b/.env.example index 3089904..287c8c5 100644 --- a/.env.example +++ b/.env.example @@ -24,6 +24,12 @@ ADMIN_PASSWORD=admin123 APP_PORT=8000 # true:调度/轮询/Outbox 在独立 Python 进程运行;false:回到单进程调试模式。 BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=true +EXECUTION_WORKER_LANES=auth,fulfillment +# 单 background 进程保持 true;若另起纯 execution worker,辅助进程设为 false。 +BACKGROUND_CONTROL_PLANE_ENABLED=true +EXECUTION_WORKER_MAX_JOBS=2 +EXECUTION_WORKER_POLL_SECONDS=1 +EXECUTION_JOB_LEASE_SECONDS=90 # 应用日志等级:DEBUG、INFO、WARNING、ERROR、CRITICAL;生产环境建议保持 INFO。 LOG_LEVEL=INFO diff --git a/docker-compose.yml b/docker-compose.yml index a9c86f1..a83ee5b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -114,6 +114,11 @@ services: # 生产默认把调度/轮询/Outbox 放到独立 Python 进程,避免重作业占住 API 的 GIL。 # 本地调试可设为 false,回到单进程兼容模式。 - BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=${BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS:-true} + - EXECUTION_WORKER_LANES=${EXECUTION_WORKER_LANES:-auth,fulfillment} + - BACKGROUND_CONTROL_PLANE_ENABLED=${BACKGROUND_CONTROL_PLANE_ENABLED:-true} + - EXECUTION_WORKER_MAX_JOBS=${EXECUTION_WORKER_MAX_JOBS:-2} + - EXECUTION_WORKER_POLL_SECONDS=${EXECUTION_WORKER_POLL_SECONDS:-1} + - EXECUTION_JOB_LEASE_SECONDS=${EXECUTION_JOB_LEASE_SECONDS:-90} # order_site 订单只读库(P0 订单读取适配层用;未配置时适配层整体降级) - ORDER_SITE_DATABASE_URL=${ORDER_SITE_DATABASE_URL:-} - ORDER_SITE_LOOKUP_ENABLED=${ORDER_SITE_LOOKUP_ENABLED:-false} diff --git a/tests/test_background_runtime.py b/tests/test_background_runtime.py index ad5351a..d39ee26 100644 --- a/tests/test_background_runtime.py +++ b/tests/test_background_runtime.py @@ -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"] diff --git a/tests/test_douyu_recharge_guard.py b/tests/test_douyu_recharge_guard.py new file mode 100644 index 0000000..364ef6d --- /dev/null +++ b/tests/test_douyu_recharge_guard.py @@ -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 diff --git a/tests/test_douyu_task_assigned_optimization.py b/tests/test_douyu_task_assigned_optimization.py index a689318..cf3ecf5 100644 --- a/tests/test_douyu_task_assigned_optimization.py +++ b/tests/test_douyu_task_assigned_optimization.py @@ -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( diff --git a/tests/test_douyu_tasks_retention.py b/tests/test_douyu_tasks_retention.py index 0ac8a52..8b8b02b 100644 --- a/tests/test_douyu_tasks_retention.py +++ b/tests/test_douyu_tasks_retention.py @@ -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): diff --git a/tests/test_execution_jobs.py b/tests/test_execution_jobs.py new file mode 100644 index 0000000..ddd354d --- /dev/null +++ b/tests/test_execution_jobs.py @@ -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" diff --git a/tests/test_login_entrypoint_audit.py b/tests/test_login_entrypoint_audit.py index 965f512..a7f09e4 100644 --- a/tests/test_login_entrypoint_audit.py +++ b/tests/test_login_entrypoint_audit.py @@ -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") diff --git a/tests/test_login_task_filters.py b/tests/test_login_task_filters.py index e884e3e..e79ca89 100644 --- a/tests/test_login_task_filters.py +++ b/tests/test_login_task_filters.py @@ -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" diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 59478f2..7fd3653 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -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 = ( diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 68aa4f7..5b858f8 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -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( diff --git a/web/backend/background_runtime.py b/web/backend/background_runtime.py index 1939c19..07859ec 100644 --- a/web/backend/background_runtime.py +++ b/web/backend/background_runtime.py @@ -2,6 +2,8 @@ from __future__ import annotations +import os + from loguru import logger from .database import SessionLocal @@ -9,8 +11,18 @@ from .database import SessionLocal _started = False +def _control_plane_enabled() -> bool: + return os.getenv("BACKGROUND_CONTROL_PLANE_ENABLED", "true").strip().lower() not in { + "0", + "false", + "no", + "off", + } + + def recover_orphaned_work() -> None: """进程启动时收敛上次中断的任务和运行记录。""" + from .models import ExecutionJob from .services.account_supply_service import ensure_default_supply_targets from .services.account_work_queue import recover_running_account_work from .services.automation.scheduler import cleanup_orphan_runs @@ -25,6 +37,14 @@ def recover_orphaned_work() -> None: db = SessionLocal() try: + durable_batch_ids = { + str(batch_id) + for (batch_id,) in ( + db.query(ExecutionJob.batch_id) + .filter(ExecutionJob.status.in_(("queued", "running"))) + .all() + ) + } cleaned_huya = cleanup_orphan_huya_tasks( db, message="任务已中断(服务重启)", @@ -33,6 +53,7 @@ def recover_orphaned_work() -> None: logger.info("启动清理虎牙残留任务: {} 条", cleaned_huya) cleaned_douyu = cleanup_orphan_douyu_tasks( db, + active_batch_ids=durable_batch_ids, message="任务已中断(服务重启)", ) if cleaned_douyu: @@ -71,6 +92,7 @@ def start_background_services() -> bool: return False from .services.automation import register_default_jobs, start_scheduler from .services.binding_poll_scheduler import start_binding_poll_scheduler + from .services.execution_worker import start_execution_job_worker from .services.integration import start_integration_outbox_worker from .services.payment_poll_scheduler import start_payment_poll_scheduler from .services.platform_fulfillment.auto_allocator import ( @@ -80,13 +102,15 @@ def start_background_services() -> bool: start_platform_fulfillment_reconciler, ) - register_default_jobs() - start_scheduler() - start_integration_outbox_worker() - start_platform_fulfillment_reconciler() - start_platform_fulfillment_auto_allocator() - start_binding_poll_scheduler() - start_payment_poll_scheduler() + start_execution_job_worker() + if _control_plane_enabled(): + register_default_jobs() + start_scheduler() + start_integration_outbox_worker() + start_platform_fulfillment_reconciler() + start_platform_fulfillment_auto_allocator() + start_binding_poll_scheduler() + start_payment_poll_scheduler() _started = True logger.info("后台服务已启动") return True @@ -98,6 +122,7 @@ def stop_background_services() -> None: return from .services.automation import stop_scheduler from .services.binding_poll_scheduler import stop_binding_poll_scheduler + from .services.execution_worker import stop_execution_job_worker from .services.integration import stop_integration_outbox_worker from .services.payment_poll_scheduler import stop_payment_poll_scheduler from .services.platform_fulfillment.auto_allocator import ( @@ -107,12 +132,14 @@ def stop_background_services() -> None: stop_platform_fulfillment_reconciler, ) - stop_payment_poll_scheduler() - stop_binding_poll_scheduler() - stop_platform_fulfillment_auto_allocator() - stop_platform_fulfillment_reconciler() - stop_integration_outbox_worker() - stop_scheduler() + if _control_plane_enabled(): + stop_payment_poll_scheduler() + stop_binding_poll_scheduler() + stop_platform_fulfillment_auto_allocator() + stop_platform_fulfillment_reconciler() + stop_integration_outbox_worker() + stop_scheduler() + stop_execution_job_worker() _started = False logger.info("后台服务已停止") diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index 2489724..0b05c44 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -485,6 +485,10 @@ "20261123_0121_douyu_tasks_retention_index.py": { "revision": "20261123_0121", "sha256": "82b5732895b1613cb017a7ea28f39b4c5b53bc48b0c92422b6ac2fca3bf7b92b" + }, + "20261123_0122_execution_jobs_recharge_guard.py": { + "revision": "20261123_0122", + "sha256": "e3549ea76a9da00d1e6e01e11d25fbb6fca3cce64b26223a8f0352a6fbec4c7d" } } } diff --git a/web/backend/migrations/versions/20261123_0122_execution_jobs_recharge_guard.py b/web/backend/migrations/versions/20261123_0122_execution_jobs_recharge_guard.py new file mode 100644 index 0000000..db35916 --- /dev/null +++ b/web/backend/migrations/versions/20261123_0122_execution_jobs_recharge_guard.py @@ -0,0 +1,231 @@ +"""add durable execution jobs and recharge duplicate guard. + +Revision ID: 20261123_0122 +Revises: 20261123_0121 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261123_0122" +down_revision: str | None = "20261123_0121" +branch_labels: str | None = None +depends_on: str | None = None + + +def _columns(table: str) -> set[str]: + return { + str(column["name"]) + for column in sa.inspect(op.get_bind()).get_columns(table) + } + + +def _indexes(table: str) -> set[str]: + return { + str(index["name"]) + for index in sa.inspect(op.get_bind()).get_indexes(table) + if index.get("name") + } + + +def upgrade() -> None: + inspector = sa.inspect(op.get_bind()) + if not inspector.has_table("execution_jobs"): + op.create_table( + "execution_jobs", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column("job_type", sa.String(length=32), nullable=False), + sa.Column("lane_scope", sa.String(length=16), nullable=False), + sa.Column("batch_id", sa.String(length=64), nullable=False), + sa.Column("payload_json", sa.JSON(), nullable=True), + sa.Column( + "status", + sa.String(length=16), + nullable=False, + server_default="queued", + ), + sa.Column( + "priority", + sa.Integer(), + nullable=False, + server_default="100", + ), + sa.Column("available_at", sa.DateTime(), nullable=False), + sa.Column( + "created_by", + sa.Integer(), + sa.ForeignKey("users.id", ondelete="RESTRICT"), + nullable=False, + ), + sa.Column( + "lease_owner", + sa.String(length=96), + nullable=False, + server_default="", + ), + sa.Column("lease_expires_at", sa.DateTime(), nullable=True), + sa.Column("heartbeat_at", sa.DateTime(), nullable=True), + sa.Column("cancel_requested_at", sa.DateTime(), nullable=True), + sa.Column( + "attempt_count", + sa.Integer(), + nullable=False, + server_default="0", + ), + sa.Column( + "max_attempts", + sa.Integer(), + nullable=False, + server_default="2", + ), + sa.Column("last_error", sa.Text(), nullable=False), + sa.Column("summary_json", sa.JSON(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + sa.Column("started_at", sa.DateTime(), nullable=True), + sa.Column("finished_at", sa.DateTime(), nullable=True), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + sa.UniqueConstraint("batch_id", name="uq_execution_jobs_batch_id"), + ) + op.create_index( + "ix_execution_jobs_claim", + "execution_jobs", + ["status", "lane_scope", "available_at", "priority", "id"], + ) + op.create_index( + "ix_execution_jobs_lease", + "execution_jobs", + ["status", "lease_expires_at"], + ) + op.create_index( + "ix_execution_jobs_created_by", + "execution_jobs", + ["created_by", "id"], + ) + + if not sa.inspect(op.get_bind()).has_table("execution_job_events"): + op.create_table( + "execution_job_events", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "job_id", + sa.BigInteger(), + sa.ForeignKey("execution_jobs.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column("batch_id", sa.String(length=64), nullable=False), + sa.Column("level", sa.String(length=16), nullable=False), + sa.Column("message", sa.Text(), nullable=False), + sa.Column("payload_json", sa.JSON(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + ) + op.create_index( + "ix_execution_job_events_batch_id", + "execution_job_events", + ["batch_id", "id"], + ) + op.create_index( + "ix_execution_job_events_created_at", + "execution_job_events", + ["created_at"], + ) + + if not sa.inspect(op.get_bind()).has_table("douyu_recharge_confirmations"): + op.create_table( + "douyu_recharge_confirmations", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column("token", sa.String(length=64), nullable=False), + sa.Column( + "user_id", + sa.Integer(), + sa.ForeignKey("users.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column("amount", sa.Integer(), nullable=False), + sa.Column("account_ids_json", sa.JSON(), nullable=False), + sa.Column("expires_at", sa.DateTime(), nullable=False), + sa.Column("used_at", sa.DateTime(), nullable=True), + sa.Column( + "created_at", + sa.DateTime(), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + sa.UniqueConstraint("token", name="uq_douyu_recharge_confirmation_token"), + ) + op.create_index( + "ix_douyu_recharge_confirmation_lookup", + "douyu_recharge_confirmations", + ["user_id", "expires_at"], + ) + + douyu_task_columns = _columns("douyu_tasks") + for name, ddl in ( + ( + "recharge_channel", + "VARCHAR(16) NOT NULL DEFAULT ''", + ), + ("recharge_amount", "INTEGER NULL"), + ("recharge_requested_at", "DATETIME NULL"), + ): + if name not in douyu_task_columns: + op.execute( + sa.text(f"ALTER TABLE douyu_tasks ADD COLUMN `{name}` {ddl}") + ) + if "ix_douyu_tasks_recharge_guard" not in _indexes("douyu_tasks"): + op.create_index( + "ix_douyu_tasks_recharge_guard", + "douyu_tasks", + [ + "account_id", + "task_type", + "recharge_channel", + "recharge_amount", + "created_at", + ], + ) + + if "recharge_duplicate_confirm_minutes" not in _columns("douyu_config"): + op.add_column( + "douyu_config", + sa.Column( + "recharge_duplicate_confirm_minutes", + sa.Integer(), + nullable=False, + server_default="10", + ), + ) + + +def downgrade() -> None: + if "recharge_duplicate_confirm_minutes" in _columns("douyu_config"): + op.drop_column("douyu_config", "recharge_duplicate_confirm_minutes") + if "ix_douyu_tasks_recharge_guard" in _indexes("douyu_tasks"): + op.drop_index("ix_douyu_tasks_recharge_guard", table_name="douyu_tasks") + douyu_task_columns = _columns("douyu_tasks") + for name in ("recharge_requested_at", "recharge_amount", "recharge_channel"): + if name in douyu_task_columns: + op.drop_column("douyu_tasks", name) + for table in ( + "douyu_recharge_confirmations", + "execution_job_events", + "execution_jobs", + ): + if sa.inspect(op.get_bind()).has_table(table): + op.drop_table(table) diff --git a/web/backend/models.py b/web/backend/models.py index 7941450..0fdaed4 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -424,6 +424,14 @@ class DouyuTask(Base): nullable=True, index=True, ) + # 鱼翅重复请求保护需要稳定列,不能依赖 JSON 内字段做窗口查询。 + recharge_channel: Mapped[str] = mapped_column( + String(16), nullable=False, default="", server_default="" + ) + recharge_amount: Mapped[int | None] = mapped_column(Integer, nullable=True) + recharge_requested_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) # 账号归属客服冗余字段,配合复合索引消除任务列表全表 filesort。 account_assigned_to: Mapped[int | None] = mapped_column( ForeignKey("users.id"), nullable=True @@ -474,6 +482,14 @@ class DouyuTask(Base): "created_at", "id", ), + Index( + "ix_douyu_tasks_recharge_guard", + "account_id", + "task_type", + "recharge_channel", + "recharge_amount", + "created_at", + ), Index( "uq_douyu_tasks_active_binding", "active_binding_key", @@ -606,6 +622,9 @@ class DouyuConfig(Base): gold_api_account_template_name: Mapped[str] = mapped_column( String(64), default="斗鱼昵称" ) + recharge_duplicate_confirm_minutes: Mapped[int] = mapped_column( + Integer, nullable=False, default=10, server_default="10" + ) gift_id: Mapped[str] = mapped_column(String(64), default="23643") skin_id: Mapped[str] = mapped_column(String(64), default="2942") updated_at: Mapped[datetime] = mapped_column( @@ -613,6 +632,111 @@ class DouyuConfig(Base): ) +class ExecutionJob(Base): + """跨进程可恢复的批次执行请求。业务任务行仍保存逐账号结果。""" + + __tablename__ = "execution_jobs" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True) + job_type: Mapped[str] = mapped_column(String(32), nullable=False) + lane_scope: Mapped[str] = mapped_column(String(16), nullable=False) + batch_id: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) + payload_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + status: Mapped[str] = mapped_column( + String(16), nullable=False, default="queued", server_default="queued" + ) + priority: Mapped[int] = mapped_column( + Integer, nullable=False, default=100, server_default="100" + ) + available_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False) + created_by: Mapped[int] = mapped_column( + ForeignKey("users.id", ondelete="RESTRICT"), nullable=False + ) + lease_owner: Mapped[str] = mapped_column( + String(96), nullable=False, default="", server_default="" + ) + lease_expires_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + heartbeat_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + cancel_requested_at: Mapped[datetime | None] = mapped_column( + UTCDateTime, nullable=True + ) + attempt_count: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + max_attempts: Mapped[int] = mapped_column( + Integer, nullable=False, default=2, server_default="2" + ) + last_error: Mapped[str] = mapped_column(Text, nullable=False, default="") + summary_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) + started_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + updated_at: Mapped[datetime] = mapped_column( + UTCDateTime, default=_utcnow, onupdate=_utcnow + ) + + __table_args__ = ( + Index( + "ix_execution_jobs_claim", + "status", + "lane_scope", + "available_at", + "priority", + "id", + ), + Index("ix_execution_jobs_lease", "status", "lease_expires_at"), + Index("ix_execution_jobs_created_by", "created_by", "id"), + ) + + +class ExecutionJobEvent(Base): + """worker 日志和任务事件,供 API 跨进程回放。""" + + __tablename__ = "execution_job_events" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True) + job_id: Mapped[int] = mapped_column( + ForeignKey("execution_jobs.id", ondelete="CASCADE"), nullable=False + ) + batch_id: Mapped[str] = mapped_column(String(64), nullable=False) + level: Mapped[str] = mapped_column(String(16), nullable=False) + message: Mapped[str] = mapped_column(Text, nullable=False, default="") + payload_json: Mapped[dict | None] = mapped_column(JSON, nullable=True) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) + + __table_args__ = ( + Index("ix_execution_job_events_batch_id", "batch_id", "id"), + Index("ix_execution_job_events_created_at", "created_at"), + ) + + +class DouyuRechargeConfirmation(Base): + """重复 API 充值的人工确认令牌。""" + + __tablename__ = "douyu_recharge_confirmations" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True) + token: Mapped[str] = mapped_column(String(64), nullable=False, unique=True) + user_id: Mapped[int] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), nullable=False + ) + amount: Mapped[int] = mapped_column(Integer, nullable=False) + account_ids_json: Mapped[list] = mapped_column(JSON, nullable=False) + expires_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False) + used_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow) + + __table_args__ = ( + Index( + "ix_douyu_recharge_confirmation_lookup", + "user_id", + "expires_at", + ), + ) + + class DouyuRoleApiLog(Base): """斗鱼角色接口原始响应与归一状态,仅追加。 diff --git a/web/backend/routers/automation.py b/web/backend/routers/automation.py index 6464340..0f2905c 100644 --- a/web/backend/routers/automation.py +++ b/web/backend/routers/automation.py @@ -148,6 +148,7 @@ def list_jobs( from ..services.binding_poll_scheduler import ( scheduler_status as binding_poll_status, ) + from ..services.execution_worker import execution_job_worker_status from ..services.payment_poll_scheduler import ( scheduler_status as payment_poll_status, ) @@ -164,6 +165,7 @@ def list_jobs( else "", "binding_poll": binding_poll_status(), "payment_poll": payment_poll_status(), + "execution_jobs": execution_job_worker_status(), }, "pending_relogin": pending_relogin, "jobs": [ diff --git a/web/backend/routers/cookies.py b/web/backend/routers/cookies.py index 875b58d..283212b 100644 --- a/web/backend/routers/cookies.py +++ b/web/backend/routers/cookies.py @@ -18,7 +18,7 @@ CK 从 `login_tasks.cookie` 迁到 `accounts.cookie`,因此本页面的**记 import csv import hashlib import io -import threading +import uuid from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import UTC, datetime @@ -27,11 +27,10 @@ from fastapi.responses import StreamingResponse from sqlalchemy import case, func, or_ from sqlalchemy.orm import Session, defer, joinedload -from ..database import WorkerSessionLocal, get_db +from ..database import get_db from ..deps import get_current_user, require_permission from ..models import Account, AuditLog, LoginTask, User -from ..models import ProxyConfig as ProxyConfigModel -from ..permissions import get_user_permissions, user_has_permission +from ..permissions import user_has_permission from ..schemas import CookieReloginRequest from ..services.account_lifecycle import on_ck_cleared from ..services.cookie_check_service import check_douyu_cookie @@ -41,7 +40,15 @@ from ..services.douyu_service import ( cookie_holding_filter, cookie_operable_filter, ) -from ..services.login_service import BatchRegistry, LoginBatchRunner, get_relogin_limits +from ..services.execution_jobs import ( + JOB_RELOGIN_BATCH, + LANE_AUTH, + TERMINAL_STATUSES, + enqueue_execution_job, + get_execution_job, + request_execution_cancel, +) +from ..services.login_service import BatchRegistry, get_relogin_limits def _fmt_dt(dt) -> str | None: @@ -648,23 +655,26 @@ def _start_relogin_accounts( status_code=400, detail="没有可重登的账号,请检查账号凭据或当前重登状态" ) - proxy = db.query(ProxyConfigModel).first() - thread_db = WorkerSessionLocal() max_login_retries, max_total_time = get_relogin_limits() - runner = LoginBatchRunner( - db=thread_db, - account_ids=account_ids, - created_by=current.id, - creator_permissions=get_user_permissions(current), - max_login_retries=max_login_retries, - max_total_time=max_total_time, - proxy_config=proxy, - log_queue=None, - loop=None, - concurrency=3, - mode="relogin", + batch_id = uuid.uuid4().hex[:12] + enqueue_execution_job( + db, + job_type=JOB_RELOGIN_BATCH, + lane_scope=LANE_AUTH, + batch_id=batch_id, + payload={ + "account_ids": account_ids, + "max_login_retries": max_login_retries, + "max_total_time": max_total_time, + "concurrency": 3, + "api_strategy": "wgapi", + "mode": "relogin", + "trigger_source": "manual", + }, + created_by=int(current.id), + priority=15, + max_attempts=2, ) - batch_id = runner.batch_id db.add( AuditLog( user_id=current.id, @@ -675,21 +685,6 @@ def _start_relogin_accounts( ) ) db.commit() - cookie_relogin_registry.register(batch_id, None, None, runner, owner_id=current.id) - - def run_relogin_batch(): - try: - runner.run() - except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 - runner._push_log("error", f"批量重新登录异常: {exc}") - message = f"重新登录异常: {exc}(旧 Cookie 已保留)" - for account_id in account_ids: - runner._mark_account_relogin_stopped(account_id, message) - runner.db.close() - finally: - cookie_relogin_registry.pop(batch_id) - - threading.Thread(target=run_relogin_batch, daemon=True).start() return { "batch_id": batch_id, "count": len(account_ids), @@ -708,15 +703,24 @@ def stop_cookie_relogin( _require_cookie_operation_perm(current) batch = cookie_relogin_registry.get(batch_id) if not batch: - raise HTTPException( - status_code=404, detail="重登批次不存在、已结束或服务已重启" - ) - if batch.get("owner_id") != current.id and not user_has_permission( - current, "login:view_all" - ): - raise HTTPException(status_code=403, detail="无权限停止该重登批次") - - batch["runner"].stop() + job = get_execution_job(db, batch_id=batch_id) + if job is None: + raise HTTPException( + status_code=404, detail="重登批次不存在、已结束或服务已重启" + ) + if job.created_by != current.id and not user_has_permission( + current, "login:view_all" + ): + raise HTTPException(status_code=403, detail="无权限停止该重登批次") + if job.status in TERMINAL_STATUSES: + raise HTTPException(status_code=404, detail="重登批次已结束") + request_execution_cancel(db, batch_id=batch_id) + else: + if batch.get("owner_id") != current.id and not user_has_permission( + current, "login:view_all" + ): + raise HTTPException(status_code=403, detail="无权限停止该重登批次") + batch["runner"].stop() db.add( AuditLog( user_id=current.id, diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index ade28cc..80eb4e9 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -3,7 +3,8 @@ from __future__ import annotations import asyncio -from datetime import UTC, datetime +import secrets +from datetime import UTC, datetime, timedelta from typing import Any, cast from weakref import WeakKeyDictionary @@ -39,10 +40,12 @@ from ..models import ( DouyuConfig, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, + DouyuRechargeConfirmation, DouyuTask, DouyuWorkbench, DouyuWorkbenchAccount, DouyuXpdGoodsSnapshot, + ExecutionJob, PlatformFulfillmentTask, User, ) @@ -89,7 +92,6 @@ from ..services.douyu_activity_query import activity_client, query_activity_good from ..services.douyu_batch_launcher import ( DOUYU_BATCH_CREATE_CONCURRENCY, DOUYU_MAX_ACTIVE_BATCHES, - start_douyu_batch, ) from ..services.douyu_exchange_result_image import ( ExchangeResultImageError, @@ -112,6 +114,17 @@ from ..services.douyu_service import ( douyu_task_payload, ensure_douyu_config, ) +from ..services.execution_jobs import ( + JOB_DOUYU_BATCH, + LANE_FULFILLMENT, + STATUS_QUEUED, + STATUS_RUNNING, + TERMINAL_STATUSES, + event_payload, + execution_events_after, + get_execution_job, + request_execution_cancel, +) from ..services.file_service import FileUploadError from ..services.file_storage import StorageUnavailableError, max_upload_size_bytes from ..services.platform_fulfillment import service as platform_fulfillment_service @@ -721,6 +734,9 @@ def _config_out(config: DouyuConfig) -> DouyuConfigOut: gold_recharge_channel=text("gold_recharge_channel"), gold_api_product_id=text("gold_api_product_id"), gold_api_account_template_name=text("gold_api_account_template_name"), + recharge_duplicate_confirm_minutes=number( + "recharge_duplicate_confirm_minutes" + ), gift_id=text("gift_id"), skin_id=text("skin_id"), updated_at=config.updated_at, @@ -1311,11 +1327,127 @@ def list_xpd_goods( return rows +def _api_recharge_duplicate_guard( + db: Session, + *, + req: DouyuTaskBatchRequest, + current: User, + config: DouyuConfig, + account_ids: list[int], + amount: int, +) -> dict[str, Any] | None: + """API 直充二次确认:令牌一次性消费,任务与令牌在同一事务落库。""" + normalized_ids = sorted({int(account_id) for account_id in account_ids}) + now = datetime.now(UTC) + if req.recharge_confirmation_token: + confirmation = ( + db.query(DouyuRechargeConfirmation) + .filter( + DouyuRechargeConfirmation.token + == req.recharge_confirmation_token, + ) + .with_for_update() + .first() + ) + stored_ids = ( + sorted( + { + int(account_id) + for account_id in (confirmation.account_ids_json or []) + } + ) + if confirmation + else [] + ) + if ( + confirmation is None + or confirmation.user_id != current.id + or confirmation.used_at is not None + or confirmation.expires_at <= now + or confirmation.amount != amount + or stored_ids != normalized_ids + ): + raise HTTPException( + status_code=409, + detail="充值确认已失效,请重新发起充值", + ) + confirmation.used_at = now + return None + + window_minutes = max( + 0, + int( + douyu_config_value( + "recharge_duplicate_confirm_minutes", + config.recharge_duplicate_confirm_minutes, + ) + or 0 + ), + ) + if window_minutes <= 0: + return None + cutoff = now - timedelta(minutes=window_minutes) + previous = ( + db.query(DouyuTask) + .filter( + DouyuTask.account_id.in_(normalized_ids), + DouyuTask.task_type == "create_gold_qr", + DouyuTask.recharge_channel == "supplier_api", + DouyuTask.recharge_amount == amount, + DouyuTask.recharge_requested_at.isnot(None), + DouyuTask.recharge_requested_at >= cutoff, + DouyuTask.status.notin_(DOUYU_ACTIVE_TASK_STATUSES), + ) + .order_by(DouyuTask.id.desc()) + .all() + ) + if not previous: + return None + duplicate_account_ids = { + int(task.account_id) for task in previous + } + account_rows = ( + db.query(Account) + .filter(Account.id.in_(duplicate_account_ids)) + .order_by(Account.id.asc()) + .all() + ) + token = secrets.token_urlsafe(32) + db.add( + DouyuRechargeConfirmation( + token=token, + user_id=int(current.id), + amount=amount, + account_ids_json=normalized_ids, + expires_at=now + timedelta(minutes=5), + ) + ) + db.commit() + names = [ + row.nickname or row.username or row.uid or f"#{row.id}" + for row in account_rows + ] + return { + "batch_id": "", + "count": 0, + "requires_confirmation": True, + "confirmation_token": token, + "window_minutes": window_minutes, + "amount": amount, + "account_names": names, + "message": ( + f"所选账号在最近 {window_minutes} 分钟内已请求过相同金额的 API 充值," + "请确认是否继续" + ), + "success": False, + } + + def _prepare_task_batch( req: DouyuTaskBatchRequest, db: Session, current: User, -) -> tuple[str, int]: +) -> dict[str, Any]: """在线程池中完成全部同步 DB 工作,避免阻塞 Uvicorn 事件循环。""" if not req.account_ids: raise HTTPException(status_code=400, detail="请选择斗鱼账号") @@ -1346,14 +1478,53 @@ def _prepare_task_batch( ) platform_task = db.get(PlatformFulfillmentTask, int(platform_task.id)) - active_batch_ids = douyu_batch_registry.active_ids() - cleanup_orphan_douyu_tasks( - db, - active_batch_ids=active_batch_ids, - statuses=DOUYU_ACTIVE_TASK_STATUSES, - message="任务已中断(无执行器接管)", + active_batches = int( + db.query(func.count(ExecutionJob.id)) + .filter( + ExecutionJob.job_type == JOB_DOUYU_BATCH, + ExecutionJob.lane_scope == LANE_FULFILLMENT, + ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING)), + ) + .scalar() + or 0 ) - _ensure_active_batch_budget(len(active_batch_ids)) + _ensure_active_batch_budget(active_batches) + config = ensure_douyu_config(db) + recharge_channel = ( + str( + douyu_config_value( + "gold_recharge_channel", + config.gold_recharge_channel, + ) + ).strip() + if req.task_type == "create_gold_qr" + else "" + ) + recharge_amount = ( + max( + 1, + int(req.payload.get("amount") or req.payload.get("gold_amount") or 1), + ) + if req.task_type == "create_gold_qr" + else None + ) + if ( + req.task_type == "create_gold_qr" + and recharge_channel == "supplier_api" + ): + guard = _api_recharge_duplicate_guard( + db, + req=req, + current=current, + config=config, + account_ids=req.account_ids, + amount=int(recharge_amount or 1), + ) + if guard is not None: + return guard + task_payload = dict(req.payload) + if req.recharge_confirmation_token: + task_payload["recharge_confirmation_used"] = True try: batch_id, count = create_douyu_planned_tasks( @@ -1362,8 +1533,11 @@ def _prepare_task_batch( req.task_type, req.handbook_scope, current.id, - req.payload, + task_payload, platform_task_id=req.platform_task_id, + concurrency=req.concurrency, + recharge_channel=recharge_channel, + recharge_amount=recharge_amount, ) except DouyuActivePaymentError as exc: raise HTTPException(status_code=409, detail=str(exc)) from exc @@ -1401,10 +1575,6 @@ def _prepare_task_batch( ) if req.task_type == "create_gold_qr": - config = ensure_douyu_config(db) - recharge_channel = str( - douyu_config_value("gold_recharge_channel", config.gold_recharge_channel) - ).strip() payment_method = ( "API 直充支付" if recharge_channel == "supplier_api" else "微信扫码支付" ) @@ -1431,6 +1601,8 @@ def _prepare_task_batch( "account_count": len(req.account_ids), "handbook_scope": req.handbook_scope, "recharge_channel": recharge_channel, + "recharge_amount": recharge_amount, + "recharge_confirmed": bool(req.recharge_confirmation_token), "payment_method": payment_method, # 仅记录充值身份,禁止在审计中写入 Cookie、密码等凭据。 "recharge_accounts": [ @@ -1447,7 +1619,7 @@ def _prepare_task_batch( ) db.commit() - return batch_id, count + return {"batch_id": batch_id, "count": count, "success": True} @router.post("/tasks/batch") @@ -1456,26 +1628,14 @@ async def create_task_batch( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): - """创建斗鱼任务记录并启动后台执行器。""" - # 同步 SQLAlchemy 段必须在线程池执行;事件循环只负责最后启动后台线程。 + """创建斗鱼任务记录和持久 execution job。""" async with _batch_create_semaphore(): - batch_id, count = await run_in_threadpool( + return await run_in_threadpool( _prepare_task_batch, req, db, current, ) - await run_in_threadpool( - start_douyu_batch, - batch_id=batch_id, - task_type=req.task_type, - payload=req.payload, - concurrency=req.concurrency, - loop=asyncio.get_running_loop(), - log_queue=asyncio.Queue(), - ) - - return {"batch_id": batch_id, "count": count, "success": True} @router.get("/tasks") @@ -1664,6 +1824,33 @@ def stop_batch( .first() is not None ) + job = get_execution_job(db, batch_id=batch_id) + if job is not None: + if job.status not in TERMINAL_STATUSES: + request_execution_cancel(db, batch_id=batch_id) + if is_recharge_batch: + record_audit( + db, + current, + action="recharge:douyu:stop", + target=f"douyu_batch:{batch_id}", + detail={"batch_id": batch_id, "mode": "durable_queue"}, + ) + db.commit() + return {"message": "已发送停止信号", "success": True} + cleaned = cleanup_orphan_douyu_tasks( + db, + batch_id=batch_id, + include_durable=True, + message="批次已结束", + ) + if cleaned: + return { + "message": f"批次已结束,已清理 {cleaned} 个残留任务", + "success": True, + } + raise HTTPException(status_code=404, detail="批次已结束") + batch = douyu_batch_registry.get(batch_id) if batch: if batch.get("finished"): @@ -1738,9 +1925,53 @@ async def ws_douyu_logs(websocket: WebSocket, batch_id: str): batch = douyu_batch_registry.get(batch_id) if not batch: - await websocket.send_json({"level": "error", "message": "批次不存在或已结束"}) - await websocket.close() - return + initial_db = WorkerSessionLocal() + try: + job = get_execution_job(initial_db, batch_id=batch_id) + finally: + initial_db.close() + if job is None: + await websocket.send_json( + {"level": "error", "message": "批次不存在或已结束"} + ) + await websocket.close() + return + last_event_id = 0 + idle_seconds = 0 + while True: + poll_db = WorkerSessionLocal() + try: + events = execution_events_after( + poll_db, + batch_id=batch_id, + after_id=last_event_id, + limit=200, + ) + job = get_execution_job(poll_db, batch_id=batch_id) + finally: + poll_db.close() + if events: + idle_seconds = 0 + for event in events: + last_event_id = int(event.id) + payload = event_payload(event) + await websocket.send_json(payload) + if payload.get("level") == "result": + await asyncio.sleep(0.1) + return + continue + if job is None or job.status in TERMINAL_STATUSES: + await websocket.send_json( + {"level": "result", "message": "批次已结束"} + ) + return + await asyncio.sleep(0.5) + idle_seconds += 0.5 + if idle_seconds >= 30: + await websocket.send_json( + {"level": "heartbeat", "message": ""} + ) + idle_seconds = 0 log_queue: asyncio.Queue = batch["log_queue"] try: diff --git a/web/backend/routers/login.py b/web/backend/routers/login.py index 67f86f3..ed558ff 100644 --- a/web/backend/routers/login.py +++ b/web/backend/routers/login.py @@ -3,7 +3,7 @@ import asyncio import csv import io -import threading +import uuid from datetime import UTC, datetime from fastapi import ( @@ -19,13 +19,22 @@ from sqlalchemy.orm import Session from ..database import WorkerSessionLocal, get_db from ..deps import authenticate_websocket, get_current_user, require_permission -from ..models import Account, LoginTask, User -from ..models import ProxyConfig as ProxyConfigModel -from ..permissions import get_user_permissions, user_has_permission +from ..models import Account, ExecutionJob, LoginTask, User +from ..permissions import user_has_permission from ..schemas import LOGIN_BATCH_MAX_ACCOUNTS, LoginBatchRequest, LoginTaskOut from ..services.audit_service import record_audit +from ..services.execution_jobs import ( + JOB_LOGIN_BATCH, + LANE_AUTH, + TERMINAL_STATUSES, + enqueue_execution_job, + event_payload, + execution_events_after, + get_execution_job, + request_execution_cancel, +) from ..services.login_failure import classify_failure, failure_kind_label -from ..services.login_service import LoginBatchRunner, batch_registry +from ..services.login_service import batch_registry router = APIRouter(prefix="/api/login", tags=["登录任务"]) @@ -161,9 +170,6 @@ async def create_batch( if not req.account_ids: raise HTTPException(status_code=400, detail="请选择账号") - # 读取代理配置 - proxy = db.query(ProxyConfigModel).first() - # 权限过滤账号 valid_ids = [] seen_ids = set() @@ -185,35 +191,26 @@ async def create_batch( action_name = "检测" if req.mode == "check" else "登录" raise HTTPException(status_code=403, detail=f"没有可{action_name}的账号") - # 在主事件循环中创建 log_queue,传给后台线程 - log_queue = asyncio.Queue() - loop = asyncio.get_running_loop() - - # 创建执行器(用独立的 DB 会话,因为在线程中运行) - thread_db = WorkerSessionLocal() - runner = LoginBatchRunner( - db=thread_db, - account_ids=valid_ids, - created_by=current.id, - creator_permissions=get_user_permissions(current), - max_login_retries=req.max_login_retries, - max_total_time=req.max_total_time, - proxy_config=proxy, - log_queue=log_queue, - loop=loop, - concurrency=req.concurrency, - api_strategy=req.api_strategy, - mode=req.mode, + batch_id = uuid.uuid4().hex[:12] + enqueue_execution_job( + db, + job_type=JOB_LOGIN_BATCH, + lane_scope=LANE_AUTH, + batch_id=batch_id, + payload={ + "account_ids": valid_ids, + "max_login_retries": req.max_login_retries, + "max_total_time": req.max_total_time, + "concurrency": req.concurrency, + "api_strategy": req.api_strategy, + "mode": req.mode, + "trigger_source": "manual", + }, + created_by=int(current.id), + priority=20, + max_attempts=2, ) - - batch_id = runner.batch_id - - # 先注册到批次注册表,再启动线程,确保 WebSocket 连接时能找到 - batch_registry.register(batch_id, log_queue, loop, runner) - - # 启动线程 - thread = threading.Thread(target=runner.run, daemon=True) - thread.start() + db.commit() # 审计:批次是谁在什么时候发起、多少个账号、什么模式。 # 自动重登与人工登录共用同一条链路,没有这条记录就无法追溯来源。 @@ -671,6 +668,7 @@ def delete_tasks( @router.post("/stop/{batch_id}") def stop_batch( batch_id: str, + db: Session = Depends(get_db), current: User = Depends(require_permission("login:batch")), ): batch = batch_registry.get(batch_id) @@ -681,7 +679,18 @@ def stop_batch( raise HTTPException(status_code=404, detail="批次已结束") batch["runner"].stop() return {"message": "已发送停止信号", "success": True} - raise HTTPException(status_code=404, detail="批次不存在或已结束") + job = get_execution_job(db, batch_id=batch_id) + if job is None: + raise HTTPException(status_code=404, detail="批次不存在") + if job.status in TERMINAL_STATUSES: + raise HTTPException(status_code=404, detail="批次已结束") + if job.created_by != current.id and not user_has_permission( + current, "login:view_all" + ): + raise HTTPException(status_code=403, detail="无权停止该批次") + request_execution_cancel(db, batch_id=batch_id) + db.commit() + return {"message": "已发送停止信号", "success": True} @router.websocket("/ws/login/{batch_id}") @@ -702,6 +711,15 @@ async def ws_login_logs(websocket: WebSocket, batch_id: str): .filter(LoginTask.batch_id == batch_id, LoginTask.created_by == user.id) .first() ) + if not owned: + owned = ( + check_db.query(ExecutionJob.id) + .filter( + ExecutionJob.batch_id == batch_id, + ExecutionJob.created_by == user.id, + ) + .first() + ) finally: check_db.close() if not owned: @@ -710,12 +728,56 @@ async def ws_login_logs(websocket: WebSocket, batch_id: str): await websocket.accept() - # 从已注册的批次中获取 log_queue(由 create_batch 创建) + # 同进程兼容模式优先使用内存队列;生产 worker 模式回放数据库事件。 batch = batch_registry.get(batch_id) if not batch: - await websocket.send_json({"level": "error", "message": "批次不存在或已结束"}) - await websocket.close() - return + initial_db = WorkerSessionLocal() + try: + job = get_execution_job(initial_db, batch_id=batch_id) + finally: + initial_db.close() + if job is None: + await websocket.send_json( + {"level": "error", "message": "批次不存在或已结束"} + ) + await websocket.close() + return + last_event_id = 0 + idle_seconds = 0 + while True: + poll_db = WorkerSessionLocal() + try: + events = execution_events_after( + poll_db, + batch_id=batch_id, + after_id=last_event_id, + limit=200, + ) + job = get_execution_job(poll_db, batch_id=batch_id) + finally: + poll_db.close() + if events: + idle_seconds = 0 + for event in events: + last_event_id = int(event.id) + payload = event_payload(event) + await websocket.send_json(payload) + if payload.get("level") == "result": + await asyncio.sleep(0.1) + return + continue + if job is None or job.status in TERMINAL_STATUSES: + await websocket.send_json( + {"level": "result", "message": "批次已结束"} + ) + return + await asyncio.sleep(0.5) + idle_seconds += 0.5 + if idle_seconds >= 30: + await websocket.send_json( + {"level": "heartbeat", "message": ""} + ) + idle_seconds = 0 log_queue: asyncio.Queue = batch["log_queue"] diff --git a/web/backend/schemas.py b/web/backend/schemas.py index 9b8dac0..f5fe295 100644 --- a/web/backend/schemas.py +++ b/web/backend/schemas.py @@ -1522,6 +1522,7 @@ class DouyuConfigOut(BaseModel): gold_recharge_channel: str = "wechat_qr" gold_api_product_id: str = "111570" gold_api_account_template_name: str = "斗鱼昵称" + recharge_duplicate_confirm_minutes: int = 10 gift_id: str = "23643" skin_id: str = "2942" updated_at: datetime | None = None @@ -1551,6 +1552,9 @@ class DouyuConfigOut(BaseModel): "gold_recharge_channel": self.gold_recharge_channel, "gold_api_product_id": self.gold_api_product_id, "gold_api_account_template_name": self.gold_api_account_template_name, + "recharge_duplicate_confirm_minutes": ( + self.recharge_duplicate_confirm_minutes + ), "gift_id": self.gift_id, "skin_id": self.skin_id, "updated_at": _isoformat(self.updated_at), @@ -1582,6 +1586,7 @@ class DouyuConfigUpdate(BaseModel): ) gold_api_product_id: str | None = Field(None, max_length=128) gold_api_account_template_name: str | None = Field(None, max_length=64) + recharge_duplicate_confirm_minutes: int | None = Field(None, ge=0, le=1440) gift_id: str | None = None skin_id: str | None = None @@ -1754,6 +1759,7 @@ class DouyuTaskBatchRequest(BaseModel): concurrency: int = Field(3, ge=1, le=10) payload: dict[str, Any] = Field(default_factory=dict) platform_task_id: int | None = Field(None, gt=0) + recharge_confirmation_token: str | None = Field(None, max_length=64) class DouyuWorkbenchAccountsUpdate(BaseModel): diff --git a/web/backend/services/automation/jobs/douyu_tasks_retention.py b/web/backend/services/automation/jobs/douyu_tasks_retention.py index 11f24ac..be2d5bc 100644 --- a/web/backend/services/automation/jobs/douyu_tasks_retention.py +++ b/web/backend/services/automation/jobs/douyu_tasks_retention.py @@ -48,7 +48,7 @@ from loguru import logger from sqlalchemy import and_, or_ from sqlalchemy.orm import Session -from ....models import AutomationJob, DouyuTask +from ....models import AutomationJob, DouyuTask, ExecutionJob, ExecutionJobEvent JOB_KEY = "douyu_tasks_retention" @@ -202,6 +202,53 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any] break per_pass[label] = deleted_this_pass + deleted_execution_events = 0 + deleted_execution_jobs = 0 + if batches < max_batches: + event_ids = [ + int(row[0]) + for row in ( + db.query(ExecutionJobEvent.id) + .filter(ExecutionJobEvent.created_at < business_cutoff) + .order_by(ExecutionJobEvent.id.asc()) + .limit(batch) + .all() + ) + ] + if event_ids: + deleted_execution_events = int( + db.query(ExecutionJobEvent) + .filter(ExecutionJobEvent.id.in_(event_ids)) + .delete(synchronize_session=False) + or 0 + ) + batches += 1 + db.commit() + if batches < max_batches: + job_ids = [ + int(row[0]) + for row in ( + db.query(ExecutionJob.id) + .filter( + ExecutionJob.status.in_(("succeeded", "failed", "cancelled")), + ExecutionJob.finished_at.isnot(None), + ExecutionJob.finished_at < business_cutoff, + ) + .order_by(ExecutionJob.id.asc()) + .limit(batch) + .all() + ) + ] + if job_ids: + deleted_execution_jobs = int( + db.query(ExecutionJob) + .filter(ExecutionJob.id.in_(job_ids)) + .delete(synchronize_session=False) + or 0 + ) + batches += 1 + db.commit() + # 注意措辞:这只说明「批次预算用光了」,**不等于**「确实还有积压」—— # 预算在上一档用完时,下一档根本没轮到执行,这里无法区分「没得删」和「没轮到」。 # 所以做成提示而非结论,措辞上也别谎称「仍有积压」。 @@ -224,6 +271,8 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any] "deleted": total_deleted, "deleted_noise": per_pass.get("noise", 0), "deleted_rest": per_pass.get("rest", 0), + "deleted_execution_events": deleted_execution_events, + "deleted_execution_jobs": deleted_execution_jobs, "batches": batches, "noise_days": noise_days, "business_days": business_days, diff --git a/web/backend/services/douyu_runner_core.py b/web/backend/services/douyu_runner_core.py index f06c4c0..6c19948 100644 --- a/web/backend/services/douyu_runner_core.py +++ b/web/backend/services/douyu_runner_core.py @@ -5,6 +5,7 @@ from __future__ import annotations import asyncio import threading import time +from collections.abc import Callable from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any @@ -106,6 +107,7 @@ class DouyuBatchRunnerCore: loop: asyncio.AbstractEventLoop | None = None, concurrency: int = 3, close_db: bool = True, + log_sink: Callable[[dict[str, Any]], None] | None = None, ): self.db = db self.close_db = close_db @@ -115,6 +117,7 @@ class DouyuBatchRunnerCore: self.log_queue = log_queue self.loop = loop self.concurrency = clamp_douyu_task_concurrency(task_type, concurrency) + self.log_sink = log_sink self._stop = threading.Event() self._counter_lock = threading.Lock() self._started = 0 @@ -179,6 +182,11 @@ class DouyuBatchRunnerCore: self.log_queue.put({"level": level, "message": message}), self.loop, ) + if self.log_sink is not None: + try: + self.log_sink({"level": level, "message": message}) + except Exception: # noqa: BLE001 - 日志落库不能中断任务 + logger.exception("写入斗鱼批次持久日志失败: {}", self.batch_id) @staticmethod def _account_name(account: Account) -> str: @@ -209,8 +217,6 @@ class DouyuBatchRunnerCore: def _push_task_event(self, task: DouyuTask) -> None: """向批次 WS 推送任务状态事件(level=task),前端即时更新不依赖轮询。""" - if not self.log_queue or not self.loop: - return try: payload = douyu_task_payload(task) except Exception: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 @@ -221,7 +227,13 @@ class DouyuBatchRunnerCore: "message": "", "task": payload, } - asyncio.run_coroutine_threadsafe(self.log_queue.put(event), self.loop) + if self.log_queue and self.loop: + asyncio.run_coroutine_threadsafe(self.log_queue.put(event), self.loop) + if self.log_sink is not None: + try: + self.log_sink(event) + except Exception: # noqa: BLE001 - 日志落库不能中断任务 + logger.exception("写入斗鱼任务事件失败: {}", self.batch_id) def _sync_platform_fulfillment(self, douyu_task_id: int, *, enabled: bool) -> None: """绑定/确认任务完成后立即刷新履约投影并写 Outbox。""" @@ -358,8 +370,9 @@ class DouyuBatchRunnerCore: task.next_run_at = now + timedelta(seconds=max(1, int(delay_seconds))) task.last_run_at = now if task.run_deadline_at is None: - task.run_deadline_at = now + timedelta(seconds=DOUYU_PAYMENT_POLL_SECONDS) - result["payment_deadline_at"] = task.run_deadline_at.isoformat() + deadline = now + timedelta(seconds=DOUYU_PAYMENT_POLL_SECONDS) + task.run_deadline_at = deadline + result["payment_deadline_at"] = deadline.isoformat() self._update_task_progress(db, task, "running", message, result) def _update_task_progress( diff --git a/web/backend/services/douyu_service.py b/web/backend/services/douyu_service.py index c6daad4..330a409 100644 --- a/web/backend/services/douyu_service.py +++ b/web/backend/services/douyu_service.py @@ -131,6 +131,7 @@ DOUYU_CONFIG_DEFAULTS = { "gold_recharge_channel": "wechat_qr", "gold_api_product_id": "111570", "gold_api_account_template_name": "斗鱼昵称", + "recharge_duplicate_confirm_minutes": 10, "gift_id": "23643", "skin_id": "2942", # 和平小店总开关,默认关(小店当前关闭;关着时一键查询完全跳过它的请求) @@ -342,6 +343,10 @@ def create_douyu_planned_tasks( created_by: int, payload: dict | None = None, platform_task_id: int | None = None, + concurrency: int = 3, + enqueue_execution: bool = True, + recharge_channel: str = "", + recharge_amount: int | None = None, ) -> tuple[str, int]: """创建斗鱼任务记录,等待后台执行器消费。""" if task_type not in SUPPORTED_DOUYU_TASK_TYPES: @@ -363,6 +368,7 @@ def create_douyu_planned_tasks( batch_id = uuid.uuid4().hex[:12] payload = payload or {} + recharge_requested_at = datetime.now(UTC) task_rows: list[tuple[DouyuTask, Account]] = [] for account in accounts: task = DouyuTask( @@ -376,6 +382,11 @@ def create_douyu_planned_tasks( result={"payload": payload} if payload else None, created_by=created_by, platform_task_id=platform_task_id, + recharge_channel=recharge_channel, + recharge_amount=recharge_amount, + recharge_requested_at=( + recharge_requested_at if recharge_amount is not None else None + ), ) db.add(task) task_rows.append((task, account)) @@ -404,7 +415,28 @@ def create_douyu_planned_tasks( } for task, account in task_rows ] - # 任务行必须先独立提交。账号事件是旁路,不能在持有任务行锁时批量插入。 + if task_rows and enqueue_execution: + from .execution_jobs import ( + JOB_DOUYU_BATCH, + LANE_FULFILLMENT, + enqueue_execution_job, + ) + + enqueue_execution_job( + db, + job_type=JOB_DOUYU_BATCH, + lane_scope=LANE_FULFILLMENT, + batch_id=batch_id, + payload={ + "task_type": task_type, + "payload": payload, + "concurrency": max(1, min(int(concurrency), 10)), + }, + created_by=int(created_by), + priority=40, + max_attempts=2, + ) + # 任务行与 execution job 必须同一事务提交;账号事件随后旁路写入。 db.commit() if events: try: diff --git a/web/backend/services/execution_jobs.py b/web/backend/services/execution_jobs.py new file mode 100644 index 0000000..dc535da --- /dev/null +++ b/web/backend/services/execution_jobs.py @@ -0,0 +1,394 @@ +"""跨进程批次执行队列。""" + +from __future__ import annotations + +import os +import socket +import uuid +from datetime import UTC, datetime, timedelta +from typing import Any + +from loguru import logger +from sqlalchemy import or_ +from sqlalchemy.orm import Session + +from ..database import WorkerSessionLocal +from ..models import ExecutionJob, ExecutionJobEvent + +JOB_LOGIN_BATCH = "login_batch" +JOB_RELOGIN_BATCH = "relogin_batch" +JOB_DOUYU_BATCH = "douyu_batch" +JOB_DOUYU_BINDING = "douyu_binding" + +LANE_AUTH = "auth" +LANE_FULFILLMENT = "fulfillment" + +STATUS_QUEUED = "queued" +STATUS_RUNNING = "running" +STATUS_SUCCEEDED = "succeeded" +STATUS_FAILED = "failed" +STATUS_CANCELLED = "cancelled" + +TERMINAL_STATUSES = frozenset({STATUS_SUCCEEDED, STATUS_FAILED, STATUS_CANCELLED}) + + +def _lease_seconds() -> int: + raw = os.getenv("EXECUTION_JOB_LEASE_SECONDS", "90") + try: + return max(30, int(raw)) + except ValueError: + return 90 + + +def execution_worker_owner() -> str: + return f"{socket.gethostname()}:{os.getpid()}:{uuid.uuid4().hex[:8]}" + + +def enqueue_execution_job( + db: Session, + *, + job_type: str, + lane_scope: str, + batch_id: str, + payload: dict[str, Any], + created_by: int, + priority: int = 100, + available_at: datetime | None = None, + max_attempts: int = 2, +) -> ExecutionJob: + existing = ( + db.query(ExecutionJob) + .filter(ExecutionJob.batch_id == batch_id) + .first() + ) + if existing is not None: + return existing + moment = available_at or datetime.now(UTC) + job = ExecutionJob( + job_type=job_type[:32], + lane_scope=lane_scope[:16], + batch_id=batch_id[:64], + payload_json=payload, + status=STATUS_QUEUED, + priority=int(priority), + available_at=moment.replace(microsecond=0), + created_by=int(created_by), + max_attempts=max(1, int(max_attempts)), + ) + db.add(job) + db.flush() + return job + + +def _recover_expired_jobs(db: Session, now: datetime) -> int: + rows = ( + db.query(ExecutionJob) + .filter( + ExecutionJob.status == STATUS_RUNNING, + or_( + ExecutionJob.lease_expires_at.is_(None), + ExecutionJob.lease_expires_at <= now, + ), + ) + .order_by(ExecutionJob.id.asc()) + .with_for_update(skip_locked=True) + .limit(50) + .all() + ) + for job in rows: + job.lease_owner = "" + job.lease_expires_at = None + job.heartbeat_at = now + job.updated_at = now + if job.cancel_requested_at is not None: + job.status = STATUS_CANCELLED + job.finished_at = now + job.last_error = "执行租约过期,且已请求取消" + elif int(job.attempt_count or 0) >= int(job.max_attempts or 1): + job.status = STATUS_FAILED + job.finished_at = now + job.last_error = "执行租约过期,重试次数已用尽" + else: + job.status = STATUS_QUEUED + job.available_at = now + job.last_error = "执行租约过期,已重新排队" + if rows: + db.commit() + return len(rows) + + +def claim_execution_jobs( + *, + lane_scopes: tuple[str, ...], + owner: str, + limit: int = 1, + now: datetime | None = None, +) -> list[ExecutionJob]: + moment = (now or datetime.now(UTC)).replace(microsecond=0) + db = WorkerSessionLocal() + try: + _recover_expired_jobs(db, moment) + rows = ( + db.query(ExecutionJob) + .filter( + ExecutionJob.status == STATUS_QUEUED, + ExecutionJob.lane_scope.in_(lane_scopes), + ExecutionJob.available_at <= moment, + ) + .order_by( + ExecutionJob.priority.asc(), + ExecutionJob.available_at.asc(), + ExecutionJob.id.asc(), + ) + .with_for_update(skip_locked=True) + .limit(max(1, int(limit))) + .all() + ) + lease_until = moment + timedelta(seconds=_lease_seconds()) + for job in rows: + job.status = STATUS_RUNNING + job.lease_owner = owner + job.lease_expires_at = lease_until + job.heartbeat_at = moment + job.started_at = job.started_at or moment + job.attempt_count = int(job.attempt_count or 0) + 1 + job.updated_at = moment + if rows: + db.commit() + for job in rows: + db.refresh(job) + return rows + except Exception: + db.rollback() + raise + finally: + db.close() + + +def heartbeat_execution_job( + *, + job_id: int, + owner: str, + now: datetime | None = None, +) -> tuple[bool, bool]: + """返回 (是否仍由本 worker 持有, 是否请求取消)。""" + moment = (now or datetime.now(UTC)).replace(microsecond=0) + db = WorkerSessionLocal() + try: + job = ( + db.query(ExecutionJob) + .filter( + ExecutionJob.id == int(job_id), + ExecutionJob.status == STATUS_RUNNING, + ExecutionJob.lease_owner == owner, + ) + .with_for_update() + .first() + ) + if job is None: + return False, False + job.lease_expires_at = moment + timedelta(seconds=_lease_seconds()) + job.heartbeat_at = moment + job.updated_at = moment + cancel_requested = job.cancel_requested_at is not None + db.commit() + return True, cancel_requested + finally: + db.close() + + +def finish_execution_job( + *, + job_id: int, + owner: str, + status: str, + summary: dict[str, Any] | None = None, + error: str = "", + now: datetime | None = None, +) -> bool: + moment = (now or datetime.now(UTC)).replace(microsecond=0) + db = WorkerSessionLocal() + try: + job = ( + db.query(ExecutionJob) + .filter( + ExecutionJob.id == int(job_id), + ExecutionJob.status == STATUS_RUNNING, + ExecutionJob.lease_owner == owner, + ) + .with_for_update() + .first() + ) + if job is None: + return False + job.status = status + job.summary_json = summary + job.last_error = (error or "")[:4000] + job.lease_owner = "" + job.lease_expires_at = None + job.finished_at = moment + job.updated_at = moment + db.commit() + return True + finally: + db.close() + + +def fail_execution_job( + *, + job_id: int, + owner: str, + error: str, + retry_delay_seconds: int = 15, + now: datetime | None = None, +) -> bool: + moment = (now or datetime.now(UTC)).replace(microsecond=0) + db = WorkerSessionLocal() + try: + job = ( + db.query(ExecutionJob) + .filter( + ExecutionJob.id == int(job_id), + ExecutionJob.status == STATUS_RUNNING, + ExecutionJob.lease_owner == owner, + ) + .with_for_update() + .first() + ) + if job is None: + return False + job.last_error = (error or "")[:4000] + job.lease_owner = "" + job.lease_expires_at = None + job.updated_at = moment + if job.cancel_requested_at is not None: + job.status = STATUS_CANCELLED + job.finished_at = moment + elif int(job.attempt_count or 0) >= int(job.max_attempts or 1): + job.status = STATUS_FAILED + job.finished_at = moment + else: + job.status = STATUS_QUEUED + job.available_at = moment + timedelta( + seconds=max(1, int(retry_delay_seconds)) + ) + db.commit() + return True + finally: + db.close() + + +def request_execution_cancel( + db: Session, + *, + batch_id: str, + now: datetime | None = None, +) -> ExecutionJob | None: + job = ( + db.query(ExecutionJob) + .filter(ExecutionJob.batch_id == batch_id) + .with_for_update() + .first() + ) + if job is None: + return None + if job.status not in TERMINAL_STATUSES and job.cancel_requested_at is None: + cancelled_at = (now or datetime.now(UTC)).replace(microsecond=0) + job.cancel_requested_at = cancelled_at + job.updated_at = cancelled_at + if job.status == STATUS_QUEUED: + job.status = STATUS_CANCELLED + job.finished_at = cancelled_at + db.flush() + return job + + +def get_execution_job( + db: Session, + *, + batch_id: str, +) -> ExecutionJob | None: + return ( + db.query(ExecutionJob) + .filter(ExecutionJob.batch_id == batch_id) + .first() + ) + + +def append_execution_event( + *, + job_id: int, + batch_id: str, + level: str, + message: str = "", + payload: dict[str, Any] | None = None, +) -> None: + db = WorkerSessionLocal() + try: + db.add( + ExecutionJobEvent( + job_id=int(job_id), + batch_id=batch_id[:64], + level=level[:16], + message=(message or "")[:8000], + payload_json=payload, + ) + ) + db.commit() + except Exception: # noqa: BLE001 - 日志旁路不能中断任务 + db.rollback() + logger.exception("写入执行任务事件失败 job_id={}", job_id) + finally: + db.close() + + +def execution_events_after( + db: Session, + *, + batch_id: str, + after_id: int = 0, + limit: int = 200, +) -> list[ExecutionJobEvent]: + return ( + db.query(ExecutionJobEvent) + .filter( + ExecutionJobEvent.batch_id == batch_id, + ExecutionJobEvent.id > int(after_id), + ) + .order_by(ExecutionJobEvent.id.asc()) + .limit(max(1, int(limit))) + .all() + ) + + +def event_payload(event: ExecutionJobEvent) -> dict[str, Any]: + payload = dict(event.payload_json or {}) + payload.setdefault("level", event.level) + payload.setdefault("message", event.message) + return payload + + +__all__ = [ + "JOB_DOUYU_BATCH", + "JOB_DOUYU_BINDING", + "JOB_LOGIN_BATCH", + "JOB_RELOGIN_BATCH", + "LANE_AUTH", + "LANE_FULFILLMENT", + "STATUS_CANCELLED", + "STATUS_FAILED", + "STATUS_QUEUED", + "STATUS_RUNNING", + "STATUS_SUCCEEDED", + "append_execution_event", + "claim_execution_jobs", + "enqueue_execution_job", + "event_payload", + "execution_events_after", + "execution_worker_owner", + "fail_execution_job", + "finish_execution_job", + "get_execution_job", + "heartbeat_execution_job", + "request_execution_cancel", +] diff --git a/web/backend/services/execution_worker.py b/web/backend/services/execution_worker.py new file mode 100644 index 0000000..f0f8cd8 --- /dev/null +++ b/web/backend/services/execution_worker.py @@ -0,0 +1,312 @@ +"""持久执行任务的 worker 消费循环。""" + +from __future__ import annotations + +import os +import threading +from concurrent.futures import Future, ThreadPoolExecutor, wait +from datetime import UTC, datetime +from typing import Any + +from loguru import logger + +from ..database import WorkerSessionLocal +from ..models import DouyuTask, ExecutionJob, ProxyConfig, User +from ..permissions import get_user_permissions +from .douyu_runner import DouyuBatchRunner +from .execution_jobs import ( + JOB_DOUYU_BATCH, + JOB_DOUYU_BINDING, + JOB_LOGIN_BATCH, + JOB_RELOGIN_BATCH, + LANE_AUTH, + LANE_FULFILLMENT, + STATUS_CANCELLED, + STATUS_SUCCEEDED, + append_execution_event, + claim_execution_jobs, + execution_worker_owner, + fail_execution_job, + finish_execution_job, + heartbeat_execution_job, +) +from .login_service import LoginBatchRunner + +DEFAULT_EXECUTION_WORKERS = 2 +DEFAULT_POLL_SECONDS = 1 + + +def _env_positive_int(name: str, default: int, minimum: int = 1) -> int: + try: + value = int(os.getenv(name, str(default))) + except ValueError: + return default + return max(minimum, value) + + +def _lane_scopes() -> tuple[str, ...]: + raw = os.getenv("EXECUTION_WORKER_LANES", "auth,fulfillment") + allowed = {LANE_AUTH, LANE_FULFILLMENT} + scopes = tuple( + item.strip().lower() + for item in raw.split(",") + if item.strip().lower() in allowed + ) + return scopes or (LANE_AUTH, LANE_FULFILLMENT) + + +class ExecutionJobWorker: + def __init__(self) -> None: + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._lock = threading.Lock() + self._executor: ThreadPoolExecutor | None = None + self._owner = execution_worker_owner() + + def start(self) -> bool: + with self._lock: + if self._thread is not None and self._thread.is_alive(): + return False + self._stop.clear() + max_workers = _env_positive_int( + "EXECUTION_WORKER_MAX_JOBS", + DEFAULT_EXECUTION_WORKERS, + ) + self._executor = ThreadPoolExecutor( + max_workers=max_workers, + thread_name_prefix="execution-job", + ) + self._thread = threading.Thread( + target=self._run, + name="execution-job-consumer", + daemon=True, + ) + self._thread.start() + logger.info( + "执行任务 worker 已启动 lanes={} max_jobs={}", + ",".join(_lane_scopes()), + max_workers, + ) + return True + + def stop(self) -> None: + self._stop.set() + with self._lock: + thread = self._thread + executor = self._executor + self._thread = None + self._executor = None + if thread is not None and thread.is_alive(): + thread.join(timeout=5) + if executor is not None: + executor.shutdown(wait=True, cancel_futures=True) + + def _run(self) -> None: + futures: set[Future] = set() + max_jobs = _env_positive_int( + "EXECUTION_WORKER_MAX_JOBS", + DEFAULT_EXECUTION_WORKERS, + ) + poll_seconds = _env_positive_int( + "EXECUTION_WORKER_POLL_SECONDS", + DEFAULT_POLL_SECONDS, + ) + while not self._stop.is_set(): + futures = {future for future in futures if not future.done()} + executor = self._executor + if executor is None: + break + slots = max_jobs - len(futures) + if slots > 0: + try: + jobs = claim_execution_jobs( + lane_scopes=_lane_scopes(), + owner=self._owner, + limit=slots, + ) + except Exception: # noqa: BLE001 - 消费循环必须存活 + logger.exception("领取执行任务失败") + jobs = [] + for job in jobs: + futures.add(executor.submit(self._run_job, job.id)) + if futures: + wait(futures, timeout=poll_seconds) + else: + self._stop.wait(poll_seconds) + + def _run_job(self, job_id: int) -> None: + db = WorkerSessionLocal() + job: ExecutionJob | None = None + runner: Any = None + cancelled = threading.Event() + heartbeat_stop = threading.Event() + try: + job = db.get(ExecutionJob, int(job_id)) + if job is None or job.status != "running": + return + payload = dict(job.payload_json or {}) + user = db.get(User, int(job.created_by)) + if user is None: + raise RuntimeError("执行任务创建人不存在") + + def log_sink(event: dict[str, Any]) -> None: + event_payload = dict(event) + level = str(event_payload.pop("level", "info") or "info") + message = str(event_payload.pop("message", "") or "") + append_execution_event( + job_id=int(job.id), + batch_id=job.batch_id, + level=level, + message=message, + payload=event_payload or None, + ) + + def heartbeat_loop() -> None: + while not heartbeat_stop.wait(5): + if self._stop.is_set(): + cancelled.set() + if runner is not None: + runner.stop() + return + held, cancel_requested = heartbeat_execution_job( + job_id=int(job.id), + owner=self._owner, + ) + if not held: + cancelled.set() + return + if cancel_requested and not cancelled.is_set(): + cancelled.set() + if runner is not None: + runner.stop() + log_sink( + { + "level": "warning", + "message": "收到停止请求,正在安全收尾", + } + ) + + heartbeat = threading.Thread( + target=heartbeat_loop, + name=f"execution-heartbeat-{job.id}", + daemon=True, + ) + heartbeat.start() + summary: dict[str, Any] = {} + if job.job_type in {JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH}: + proxy = db.query(ProxyConfig).first() + runner = LoginBatchRunner( + db=db, + account_ids=[ + int(value) + for value in payload.get("account_ids", []) + ], + created_by=int(job.created_by), + creator_permissions=get_user_permissions(user), + max_login_retries=int(payload.get("max_login_retries", 0) or 0), + max_total_time=float(payload.get("max_total_time", 300) or 0), + proxy_config=proxy, + log_queue=None, + loop=None, + concurrency=int(payload.get("concurrency", 3) or 3), + api_strategy=str(payload.get("api_strategy", "wgapi") or "wgapi"), + mode=str(payload.get("mode", "login") or "login"), + trigger_source=str(payload.get("trigger_source", "manual") or "manual"), + batch_id=job.batch_id, + log_sink=log_sink, + ) + runner.run() + elif job.job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}: + if int(job.attempt_count or 0) > 1: + # 进程中断会留下 pending/running 的初始任务;支付轮询有独立 + # queue_lane,不能被重放。重试只重置尚无后置 lane 的行。 + db.query(DouyuTask).filter( + DouyuTask.batch_id == job.batch_id, + DouyuTask.status.in_(("planned", "pending", "running")), + DouyuTask.queue_lane == "", + ).update( + { + DouyuTask.status: "planned", + DouyuTask.message: "执行进程中断,已恢复排队", + }, + synchronize_session=False, + ) + db.commit() + runner = DouyuBatchRunner( + db=db, + batch_id=job.batch_id, + task_type=str(payload.get("task_type") or ""), + payload=dict(payload.get("payload") or {}), + log_queue=None, + loop=None, + concurrency=int(payload.get("concurrency", 3) or 3), + close_db=False, + log_sink=log_sink, + ) + runner.run() + else: + raise RuntimeError(f"不支持的执行任务类型: {job.job_type}") + summary = {"finished_at": datetime.now(UTC).isoformat()} + held, cancel_requested = heartbeat_execution_job( + job_id=int(job.id), + owner=self._owner, + ) + if not held: + return + finish_execution_job( + job_id=int(job.id), + owner=self._owner, + status=( + STATUS_CANCELLED + if cancelled.is_set() or cancel_requested + else STATUS_SUCCEEDED + ), + summary=summary, + ) + except Exception as exc: # noqa: BLE001 - job 边界必须收口 + logger.exception("执行任务失败 job_id={}", job_id) + append_execution_event( + job_id=int(job_id), + batch_id=str(job.batch_id) if job is not None else "", + level="error", + message=f"{type(exc).__name__}: {exc}", + ) + fail_execution_job( + job_id=int(job_id), + owner=self._owner, + error=f"{type(exc).__name__}: {exc}", + ) + finally: + heartbeat_stop.set() + db.close() + + +execution_job_worker = ExecutionJobWorker() + + +def start_execution_job_worker() -> bool: + return execution_job_worker.start() + + +def stop_execution_job_worker() -> None: + execution_job_worker.stop() + + +def execution_job_worker_status() -> dict[str, Any]: + thread = execution_job_worker._thread + return { + "running": bool(thread and thread.is_alive()), + "lanes": list(_lane_scopes()), + "max_jobs": _env_positive_int( + "EXECUTION_WORKER_MAX_JOBS", + DEFAULT_EXECUTION_WORKERS, + ), + "owner": execution_job_worker._owner, + } + + +__all__ = [ + "execution_job_worker_status", + "start_execution_job_worker", + "stop_execution_job_worker", +] diff --git a/web/backend/services/login_service.py b/web/backend/services/login_service.py index 59a0bea..fd70d8e 100644 --- a/web/backend/services/login_service.py +++ b/web/backend/services/login_service.py @@ -5,10 +5,11 @@ import os import threading import time import uuid +from collections.abc import Callable from concurrent.futures import as_completed from datetime import UTC, datetime from types import SimpleNamespace -from typing import cast +from typing import Any, cast from loguru import logger from sqlalchemy import and_, func, or_ @@ -292,7 +293,7 @@ def _persist_login_cookie_verification( "identity": { "uid": account.uid, "username": account.username, - "nickname": detail.get("nickname") or "", + "nickname": (detail or {}).get("nickname") or "", "nickname_source": "session", }, "session": check_result, @@ -338,6 +339,8 @@ class LoginBatchRunner: api_strategy: str = "wgapi", mode: str = "login", trigger_source: str = "manual", + batch_id: str | None = None, + log_sink: Callable[[dict[str, Any]], None] | None = None, ): self.db = db self.account_ids = account_ids @@ -350,7 +353,8 @@ class LoginBatchRunner: self.proxy_config = _snapshot_proxy_config(proxy_config) self.log_queue = log_queue self.loop = loop - self.batch_id = uuid.uuid4().hex[:12] + self.batch_id = (batch_id or uuid.uuid4().hex[:12])[:64] + self.log_sink = log_sink self.concurrency = max( 1, min(concurrency, 10, login_concurrency_limit(db)), @@ -441,6 +445,11 @@ class LoginBatchRunner: self.log_queue.put({"level": level, "message": message}), self.loop, ) + if self.log_sink is not None: + try: + self.log_sink({"level": level, "message": message}) + except Exception: # noqa: BLE001 - 日志落库不能中断登录 + logger.exception("写入登录批次持久日志失败: {}", self.batch_id) def _resolve_static_proxy(self) -> tuple[dict | None, str]: """解析静态代理配置。""" diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index 077b2fc..9e7fea4 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -21,7 +21,11 @@ from ..account_binding import ( pending_binding_role_from_result, ) from ..business_events import record_douyu_task_started -from ..douyu_batch_launcher import start_douyu_batch +from ..execution_jobs import ( + JOB_DOUYU_BINDING, + LANE_FULFILLMENT, + enqueue_execution_job, +) from .binding_status import ( _binding_failure_issue, _binding_failure_raw_message, @@ -129,14 +133,21 @@ def start_binding_sync( detail={"bindTaskId": bind_task.id}, ) _emit_order_site_binding_state(db, task.id) - db.commit() - start_douyu_batch( + enqueue_execution_job( + db, + job_type=JOB_DOUYU_BINDING, + lane_scope=LANE_FULFILLMENT, batch_id=batch_id, - task_type="get_bind_qr", - payload={}, - concurrency=1, - capture_event_loop=False, + payload={ + "task_type": "get_bind_qr", + "payload": {}, + "concurrency": 1, + }, + created_by=int(current.id), + priority=10, + max_attempts=2, ) + db.commit() return get_task_detail(db, task.id) @@ -368,14 +379,21 @@ def confirm_binding_sync(db: Session, *, task_id: int, current: User) -> dict[st detail={"confirmTaskId": confirm_task.id}, ) _emit_order_site_binding_state(db, task.id) - db.commit() - start_douyu_batch( + enqueue_execution_job( + db, + job_type=JOB_DOUYU_BINDING, + lane_scope=LANE_FULFILLMENT, batch_id=batch_id, - task_type="confirm_bind", - payload={}, - concurrency=1, - capture_event_loop=False, + payload={ + "task_type": "confirm_bind", + "payload": {}, + "concurrency": 1, + }, + created_by=int(current.id), + priority=10, + max_attempts=1, ) + db.commit() return get_task_detail(db, task.id) diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index a9a5364..a805706 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -942,6 +942,7 @@ export interface DouyuConfig { gold_recharge_channel: "wechat_qr" | "supplier_api"; gold_api_product_id: string; gold_api_account_template_name: string; + recharge_duplicate_confirm_minutes: number; gift_id: string; skin_id: string; updated_at: string | null; @@ -958,12 +959,19 @@ export interface DouyuTaskBatchRequest { concurrency?: number; payload?: Record; platform_task_id?: number; + recharge_confirmation_token?: string; } export interface DouyuTaskBatchResult { batch_id: string; count: number; success: boolean; + requires_confirmation?: boolean; + confirmation_token?: string; + window_minutes?: number; + amount?: number; + account_names?: string[]; + message?: string; } export interface DouyuTaskItem { diff --git a/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx b/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx index 68cafe1..ec2bcca 100644 --- a/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx +++ b/web/frontend/src/pages/douyu-tasks/DouyuTasksPage.tsx @@ -1025,6 +1025,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) taskType: string, accountIds?: number[], extraPayload: Record = {}, + rechargeConfirmationToken?: string, ) => { const ids = accountIds || selectedIds; if (ids.length === 0) { @@ -1068,7 +1069,40 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) handbook_scope: handbook, concurrency: batchConcurrency, payload, + recharge_confirmation_token: rechargeConfirmationToken, }); + if (result.requires_confirmation) { + const accountText = (result.account_names || []).join('、'); + Modal.confirm({ + title: '重复 API 充值确认', + content: ( + + {result.message} + + {accountText ? `账号:${accountText}` : ''} + {accountText ? ';' : ''} + 金额:{result.amount ?? goldAmount} 鱼翅 + + + ), + okText: '确认充值', + cancelText: '取消', + onOk: async () => { + const confirmationToken = result.confirmation_token; + if (!confirmationToken) { + message.error('充值确认令牌缺失,请重新发起'); + return; + } + await startTask( + taskType, + ids, + extraPayload, + confirmationToken, + ); + }, + }); + return null; + } // 只有本页面创建的批次才允许主动弹二维码,防止其他工作台/浏览器的任务打扰当前操作。 locallyStartedBatchIds.current.add(result.batch_id); if ( @@ -3055,6 +3089,20 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind }) {configFormValues.gold_recharge_channel === 'supplier_api' && ( <> + + 重复充值确认窗口(分钟,0=关闭) + setConfigFormValues((prev) => prev ? { + ...prev, + recharge_duplicate_confirm_minutes: Number(value) || 0, + } : prev)} + /> + {[ { label: '供应商商品 ID', key: 'gold_api_product_id' }, { label: '充值账号模板名(值为斗鱼昵称)', key: 'gold_api_account_template_name' },