From 2ea105a924adfb3a1516e69d175a27bc5d2bb60b Mon Sep 17 00:00:00 2001 From: yml Date: Sun, 29 Nov 2026 11:24:35 +0800 Subject: [PATCH] =?UTF-8?q?fix(worker):=20=E4=BC=98=E5=8C=96=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E6=B1=A0=E5=AE=B9=E9=87=8F=E6=8B=86=E5=88=86=E3=80=81?= =?UTF-8?q?=E5=B9=B6=E5=8F=91=E5=85=A5=E9=98=9F=E4=B8=8E=E4=BA=8B=E4=BB=B6?= =?UTF-8?q?=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 30 ++- README.md | 2 +- docker-compose.yml | 36 +-- pyproject.toml | 2 +- tests/test_account_capability_refresh_job.py | 57 +++++ tests/test_account_platform_foundation.py | 77 ++++++ tests/test_douyu_task_concurrency.py | 41 ++++ tests/test_execution_jobs.py | 225 +++++++++++++++++- uv.lock | 2 +- web/backend/database.py | 48 +++- web/backend/services/account_value.py | 32 ++- web/backend/services/account_work_queue.py | 91 +++++-- web/backend/services/douyu_runner.py | 11 +- web/backend/services/douyu_runner_core.py | 154 ++++++++---- web/backend/services/execution_jobs.py | 185 ++++++++++++-- web/backend/services/execution_worker.py | 62 +++-- web/backend/services/login_service.py | 3 + .../platform_fulfillment/account_selector.py | 105 ++++---- 18 files changed, 956 insertions(+), 207 deletions(-) diff --git a/.env.example b/.env.example index 4bf4763..6ef280f 100644 --- a/.env.example +++ b/.env.example @@ -103,42 +103,46 @@ DEV_DB_PORT=3307 # 数据库连接策略(仅 MySQL 生效) # null=每次 Session 关闭即断开物理连接;queue=复用连接池。 +# 分进程模式下(BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=true),api 进程的 worker 池 +# 会自动收紧为 4+4=8,background 进程的主池自动收紧为 2+2=4,双进程理论总上限 +# 为 (20+20+4+4) + (2+2+24+16) = 92,低于 MySQL 默认 max_connections=151。 DB_POOL_MODE=queue WORKER_DB_POOL_MODE=queue DB_POOL_SIZE=20 DB_MAX_OVERFLOW=20 -WORKER_DB_POOL_SIZE=10 -WORKER_DB_MAX_OVERFLOW=4 +WORKER_DB_POOL_SIZE=24 +WORKER_DB_MAX_OVERFLOW=16 DEPLOY_STARTUP_TIMEOUT_SECONDS=1800 DB_POOL_TIMEOUT=30 +WORKER_DB_POOL_TIMEOUT=60 DB_POOL_RECYCLE=1800 # 行锁 10 秒仍未拿到就失败,避免把连接池和请求线程长期堵住。 DB_LOCK_WAIT_TIMEOUT=10 # 斗鱼批次创建并发与全局活跃量背压。 DOUYU_BATCH_CREATE_CONCURRENCY=2 -DOUYU_BATCH_TASK_CONCURRENCY=5 -DOUYU_PAYMENT_QR_CONCURRENCY=10 +DOUYU_BATCH_TASK_CONCURRENCY=8 +DOUYU_PAYMENT_QR_CONCURRENCY=8 DOUYU_MAX_ACTIVE_BATCHES=10 -# 一键查询使用独立任务槽;普通查询仍为 3 个 worker。 +# 一键查询使用独立任务槽;普通查询仍为 4 个 worker。 DOUYU_MAX_ACTIVE_OVERVIEW_TASKS=5 -# 业务域任务槽。支付出码与到账轮询分离后,各自按实际耗时独立限流。 +# 业务域任务槽。支付出码与到账轮询分离后,各自按实际耗时独立限流,总量匹配 worker 连接池。 TASK_LANE_BATCH_COORDINATOR_WORKERS=2 TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT=2 -TASK_LANE_INTERACTIVE_BINDING_WORKERS=3 +TASK_LANE_INTERACTIVE_BINDING_WORKERS=4 TASK_LANE_BINDING_POLL_WORKERS=6 TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT=6 TASK_LANE_LOGIN_WORKERS=4 TASK_LANE_ACCOUNT_CHECK_WORKERS=4 -TASK_LANE_ACCOUNT_SYNC_WORKERS=10 +TASK_LANE_ACCOUNT_SYNC_WORKERS=6 # 账号同步队列待处理水位。通用供给只能占低水位,剩余预留给有明确订单的补货。 ACCOUNT_SYNC_QUEUE_TARGET_PENDING=60 ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING=20 TASK_LANE_OVERVIEW_QUERY_WORKERS=5 -TASK_LANE_QUERY_BATCH_WORKERS=3 -TASK_LANE_PAYMENT_QR_WORKERS=10 -TASK_LANE_PAYMENT_POLL_WORKERS=3 -TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=3 -TASK_LANE_OPS_WRITE_WORKERS=2 +TASK_LANE_QUERY_BATCH_WORKERS=4 +TASK_LANE_PAYMENT_QR_WORKERS=8 +TASK_LANE_PAYMENT_POLL_WORKERS=4 +TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=4 +TASK_LANE_OPS_WRITE_WORKERS=4 DOUYU_MAX_ACTIVE_TASKS=250 DOUYU_PROBE_CACHE_SECONDS=30 DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=0.2 diff --git a/README.md b/README.md index 2a04aae..5c63cf4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.18)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.21)。 ## 能做什么 diff --git a/docker-compose.yml b/docker-compose.yml index 8e4271b..1daaeb0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -44,28 +44,28 @@ services: - DB_POOL_RECYCLE=${DB_POOL_RECYCLE:-1800} - DB_LOCK_WAIT_TIMEOUT=${DB_LOCK_WAIT_TIMEOUT:-10} - WORKER_DB_POOL_MODE=${WORKER_DB_POOL_MODE:-queue} - - WORKER_DB_POOL_SIZE=${WORKER_DB_POOL_SIZE:-10} - - WORKER_DB_MAX_OVERFLOW=${WORKER_DB_MAX_OVERFLOW:-4} - - WORKER_DB_POOL_TIMEOUT=${WORKER_DB_POOL_TIMEOUT:-30} + - WORKER_DB_POOL_SIZE=${WORKER_DB_POOL_SIZE:-24} + - WORKER_DB_MAX_OVERFLOW=${WORKER_DB_MAX_OVERFLOW:-16} + - WORKER_DB_POOL_TIMEOUT=${WORKER_DB_POOL_TIMEOUT:-60} - DOUYU_BATCH_CREATE_CONCURRENCY=${DOUYU_BATCH_CREATE_CONCURRENCY:-4} - - DOUYU_BATCH_TASK_CONCURRENCY=${DOUYU_BATCH_TASK_CONCURRENCY:-10} - - DOUYU_PAYMENT_QR_CONCURRENCY=${DOUYU_PAYMENT_QR_CONCURRENCY:-15} + - DOUYU_BATCH_TASK_CONCURRENCY=${DOUYU_BATCH_TASK_CONCURRENCY:-8} + - DOUYU_PAYMENT_QR_CONCURRENCY=${DOUYU_PAYMENT_QR_CONCURRENCY:-8} - DOUYU_MAX_ACTIVE_BATCHES=${DOUYU_MAX_ACTIVE_BATCHES:-25} - - DOUYU_MAX_ACTIVE_OVERVIEW_TASKS=${DOUYU_MAX_ACTIVE_OVERVIEW_TASKS:-10} + - DOUYU_MAX_ACTIVE_OVERVIEW_TASKS=${DOUYU_MAX_ACTIVE_OVERVIEW_TASKS:-5} - TASK_LANE_BATCH_COORDINATOR_WORKERS=${TASK_LANE_BATCH_COORDINATOR_WORKERS:-6} - TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT=${TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT:-6} - - TASK_LANE_INTERACTIVE_BINDING_WORKERS=${TASK_LANE_INTERACTIVE_BINDING_WORKERS:-6} - - TASK_LANE_BINDING_POLL_WORKERS=${TASK_LANE_BINDING_POLL_WORKERS:-12} - - TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT=${TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT:-12} - - TASK_LANE_LOGIN_WORKERS=${TASK_LANE_LOGIN_WORKERS:-8} - - TASK_LANE_ACCOUNT_CHECK_WORKERS=${TASK_LANE_ACCOUNT_CHECK_WORKERS:-8} - - TASK_LANE_ACCOUNT_SYNC_WORKERS=${TASK_LANE_ACCOUNT_SYNC_WORKERS:-10} - - TASK_LANE_OVERVIEW_QUERY_WORKERS=${TASK_LANE_OVERVIEW_QUERY_WORKERS:-10} - - TASK_LANE_QUERY_BATCH_WORKERS=${TASK_LANE_QUERY_BATCH_WORKERS:-10} - - TASK_LANE_PAYMENT_QR_WORKERS=${TASK_LANE_PAYMENT_QR_WORKERS:-12} - - TASK_LANE_PAYMENT_POLL_WORKERS=${TASK_LANE_PAYMENT_POLL_WORKERS:-6} - - TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=${TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT:-6} - - TASK_LANE_OPS_WRITE_WORKERS=${TASK_LANE_OPS_WRITE_WORKERS:-6} + - TASK_LANE_INTERACTIVE_BINDING_WORKERS=${TASK_LANE_INTERACTIVE_BINDING_WORKERS:-4} + - TASK_LANE_BINDING_POLL_WORKERS=${TASK_LANE_BINDING_POLL_WORKERS:-6} + - TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT=${TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT:-6} + - TASK_LANE_LOGIN_WORKERS=${TASK_LANE_LOGIN_WORKERS:-4} + - TASK_LANE_ACCOUNT_CHECK_WORKERS=${TASK_LANE_ACCOUNT_CHECK_WORKERS:-4} + - TASK_LANE_ACCOUNT_SYNC_WORKERS=${TASK_LANE_ACCOUNT_SYNC_WORKERS:-6} + - TASK_LANE_OVERVIEW_QUERY_WORKERS=${TASK_LANE_OVERVIEW_QUERY_WORKERS:-5} + - TASK_LANE_QUERY_BATCH_WORKERS=${TASK_LANE_QUERY_BATCH_WORKERS:-4} + - TASK_LANE_PAYMENT_QR_WORKERS=${TASK_LANE_PAYMENT_QR_WORKERS:-8} + - TASK_LANE_PAYMENT_POLL_WORKERS=${TASK_LANE_PAYMENT_POLL_WORKERS:-4} + - TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=${TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT:-4} + - TASK_LANE_OPS_WRITE_WORKERS=${TASK_LANE_OPS_WRITE_WORKERS:-4} - DOUYU_MAX_ACTIVE_TASKS=${DOUYU_MAX_ACTIVE_TASKS:-500} - DOUYU_PROBE_CACHE_SECONDS=${DOUYU_PROBE_CACHE_SECONDS:-30} - DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=${DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS:-0.2} diff --git a/pyproject.toml b/pyproject.toml index 6f52d7e..27be495 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.18" +version = "0.4.21" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_account_capability_refresh_job.py b/tests/test_account_capability_refresh_job.py index d7d679d..b776b54 100644 --- a/tests/test_account_capability_refresh_job.py +++ b/tests/test_account_capability_refresh_job.py @@ -614,3 +614,60 @@ def test_default_enabled_job_is_created_enabled(db, monkeypatch): .one() ) assert row.enabled is True + + +def test_multi_commodity_refresh_handles_missing_and_due_states(db): + from web.backend.services.platform_fulfillment.account_selector import ( + capability_refresh_candidate_accounts, + ) + + missing_one = _account(db, "cap-multi-missing-one") + fresh_storehome_missing = _account(db, "cap-multi-fresh-sh") + due_one = _account(db, "cap-multi-due-one") + all_fresh = _account(db, "cap-multi-all-fresh") + + # missing_one 只有 C1 新鲜,缺少 C2,且 storehome 过期 -> 应被选中 + _state(db, missing_one, commodity_id="C1", valid_until=NOW + timedelta(hours=1)) + # fresh_storehome_missing 只有 C1 新鲜,缺少 C2,但 storehome 新鲜 -> 不应重复补扫 + _state( + db, + fresh_storehome_missing, + commodity_id="C1", + valid_until=NOW + timedelta(hours=1), + ) + db.add( + AccountSyncState( + account_id=fresh_storehome_missing.id, + platform="douyu", + domain="storehome", + status="success", + last_success_at=NOW, + valid_until=NOW + timedelta(hours=1), + ) + ) + # due_one 两个都有,但 C2 已过期 -> 即使 storehome 新鲜也应被选中 + _state(db, due_one, commodity_id="C1", valid_until=NOW + timedelta(hours=1)) + _state(db, due_one, commodity_id="C2", valid_until=NOW - timedelta(minutes=1)) + db.add( + AccountSyncState( + account_id=due_one.id, + platform="douyu", + domain="storehome", + status="success", + last_success_at=NOW, + valid_until=NOW + timedelta(hours=1), + ) + ) + # all_fresh 两个都新鲜 -> 不应被选中 + _state(db, all_fresh, commodity_id="C1", valid_until=NOW + timedelta(hours=1)) + _state(db, all_fresh, commodity_id="C2", valid_until=NOW + timedelta(hours=1)) + db.commit() + + selected = capability_refresh_candidate_accounts( + db, + commodity_ids=["C1", "C2"], + scope="elite", + limit=10, + now=NOW, + ) + assert {row.id for row in selected} == {missing_one.id, due_one.id} diff --git a/tests/test_account_platform_foundation.py b/tests/test_account_platform_foundation.py index 294a34e..aa41d65 100644 --- a/tests/test_account_platform_foundation.py +++ b/tests/test_account_platform_foundation.py @@ -536,3 +536,80 @@ def test_login_quota_configuration_route_updates_all_categories(db): assert updated["relogin_high_value_daily_limit"] == 240 assert updated["failure_pause_ratio"] == 35 assert loaded["login_concurrency"] == 3 + + +def test_enqueue_account_work_survives_repeatable_read_integrity_race(db): + from tests.support.db import make_test_session + + account = _account("queue-race-account") + db.add(account) + db.commit() + + # 先开启 db 的 REPEATABLE READ 快照,再由另一会话提交同一工作项 + assert db.query(AccountWorkItem).count() == 0 + other = make_test_session() + try: + committed = enqueue_account_work( + other, + account_id=account.id, + work_type="storehome_sync", + priority=20, + ) + other.commit() + committed_id = int(committed.id) + finally: + other.close() + + # db 的旧快照看不到 committed,INSERT 会撞唯一键,但不能抛 NoResultFound + reused = enqueue_account_work( + db, + account_id=account.id, + work_type="storehome_sync", + priority=10, + ) + assert int(reused.id) == committed_id + db.commit() + + # 如果并发项在另一会话中刚被完成并清空 active_dedupe_key,再次撞锁时也能重新入队 + other = make_test_session() + try: + current = other.get(AccountWorkItem, committed_id) + assert current is not None + complete_account_work(other, current) + other.commit() + finally: + other.close() + + # 人工模拟同一快照里先误判存在冲突后被完成:重新入队应得到一条新记录 + fresh = enqueue_account_work( + db, + account_id=account.id, + work_type="storehome_sync", + priority=10, + ) + db.commit() + assert int(fresh.id) != committed_id + + +def test_enqueue_account_work_raises_integrity_error_when_retries_exhausted( + db, monkeypatch +): + import pytest + from sqlalchemy.exc import IntegrityError + + account = _account("queue-race-exhausted") + db.add(account) + db.commit() + + def always_conflict() -> None: + raise IntegrityError("INSERT", {}, Exception("Duplicate entry")) + + monkeypatch.setattr(db, "flush", always_conflict) + + with pytest.raises(IntegrityError): + enqueue_account_work( + db, + account_id=account.id, + work_type="storehome_sync", + priority=10, + ) diff --git a/tests/test_douyu_task_concurrency.py b/tests/test_douyu_task_concurrency.py index 312dd43..df7c8d1 100644 --- a/tests/test_douyu_task_concurrency.py +++ b/tests/test_douyu_task_concurrency.py @@ -2128,3 +2128,44 @@ def test_poll_bind_role_once_records_mismatched_cjm_and_ignores_bound_action_rol assert "妎䏓" in task.message assert task.result["last_mismatched_role"]["role_name"] == "妎朊" assert [m["role_name"] for m in task.result["mismatched_roles"]] == ["妎朊"] + + +def test_mark_task_reuses_worker_session_without_nested_checkout(db, monkeypatch): + from web.backend import database as database_module + from web.backend.services.platform_fulfillment import service as pf_service + + _, _, task = _fixtures(db, status="running") + task.task_type = "confirm_bind" + task.handbook_scope = "elite" + db.commit() + + monkeypatch.setattr( + database_module, + "WorkerSessionLocal", + lambda: (_ for _ in ()).throw(AssertionError("收尾钩子不能再嵌套借用 WorkerSessionLocal")), + ) + seen_dbs: list[tuple[str, object]] = [] + monkeypatch.setattr( + pf_service, + "sync_task_from_binding_runner", + lambda session, *, douyu_task_id: seen_dbs.append(("sync", session)) or 0, + ) + monkeypatch.setattr( + pf_service, + "verify_active_binding_for_douyu_task", + lambda session, *, douyu_task_id, actor_id=None: seen_dbs.append(("verify", session)) or None, + ) + monkeypatch.setattr( + pf_service, + "refresh_active_exchange_eligibility_for_account", + lambda session, *, account_id, scope, actor_id=None: seen_dbs.append(("eligibility", session)) or None, + ) + + runner = DouyuBatchRunner(db, task.batch_id, "confirm_bind", close_db=False) + runner._mark_task(db, task, "success", "确认绑定成功") + + assert seen_dbs == [ + ("sync", db), + ("verify", db), + ("eligibility", db), + ] diff --git a/tests/test_execution_jobs.py b/tests/test_execution_jobs.py index 0ae4b0c..b622420 100644 --- a/tests/test_execution_jobs.py +++ b/tests/test_execution_jobs.py @@ -9,14 +9,15 @@ 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, JOB_DOUYU_BATCH, + JOB_LOGIN_BATCH, LANE_AUTH, LANE_FULFILLMENT, STATUS_CANCELLED, STATUS_RUNNING, claim_execution_jobs, enqueue_execution_job, + execution_events_after, finish_execution_job, heartbeat_execution_job, request_execution_cancel, @@ -242,3 +243,225 @@ def test_auth_batches_cannot_starve_fulfillment_lane(db, monkeypatch): finally: release.set() worker.stop() + + +def test_execution_worker_batches_events_and_closes_douyu_db(db, monkeypatch): + user = _user(db, "execution-batch-events") + job = enqueue_execution_job( + db, + job_type=JOB_DOUYU_BATCH, + lane_scope=LANE_FULFILLMENT, + batch_id="exec-batch-events", + payload={"task_type": "query_points", "payload": {}, "concurrency": 1}, + created_by=int(user.id), + ) + db.commit() + worker = execution_worker.ExecutionJobWorker() + claimed = claim_execution_jobs( + lane_scopes=(LANE_FULFILLMENT,), + owner=worker._owner, + limit=1, + ) + assert [row.id for row in claimed] == [job.id] + seen: dict = {} + + class FakeDouyuRunner: + def __init__(self, **kwargs): + seen.update(kwargs) + + def run(self): + seen["log_sink"]({"level": "info", "message": "step-1"}) + seen["log_sink"]({"level": "info", "message": "step-2"}) + seen["ran"] = True + + monkeypatch.setattr(execution_worker, "DouyuBatchRunner", FakeDouyuRunner) + worker._event_writer.start() + try: + worker._run_job(int(job.id)) + finally: + worker._event_writer.stop() + + assert seen.get("ran") is True + assert seen.get("close_db") is True + db.rollback() + events = execution_events_after(db, batch_id="exec-batch-events") + assert [item.message for item in events] == ["step-1", "step-2"] + + +def test_douyu_batch_runner_closes_coordinator_session_before_task_execution( + db, monkeypatch +): + from tests.support.db import make_test_session + from web.backend.models import Account, DouyuTask + from web.backend.services.douyu_runner import DouyuBatchRunner + + user = _user(db, "douyu-close-session") + account = Account( + username="douyu-close-acc", + password="p", + email="douyu-close-acc@example.com", + email_password="ep", + ) + db.add(account) + db.flush() + task = DouyuTask( + batch_id="douyu-close-batch", + account_id=account.id, + task_type="query_points", + status="planned", + created_by=user.id, + ) + db.add(task) + db.commit() + + coord_db = make_test_session() + closed = {"called": False} + orig_close = coord_db.close + + def tracked_close() -> None: + closed["called"] = True + orig_close() + + monkeypatch.setattr(coord_db, "close", tracked_close) + runner = DouyuBatchRunner( + coord_db, + "douyu-close-batch", + "query_points", + close_db=True, + ) + observed_closed_during_exec: list[bool] = [] + monkeypatch.setattr( + runner, + "_execute_one", + lambda _task_id, _cfg, _total: observed_closed_during_exec.append( + closed["called"] + ), + ) + + runner.run() + + assert observed_closed_during_exec == [True] + assert closed["called"] is True + + +def test_event_batch_writer_flush_timeout_preserves_fifo_and_bounds_time(monkeypatch): + from web.backend.services import execution_jobs + + flushed_messages: list[str] = [] + gate = threading.Event() + first_started = threading.Event() + + def fake_append(events: list[dict]) -> bool: + messages = [str(item["message"]) for item in events] + if "in-flight" in messages: + first_started.set() + gate.wait(2) + flushed_messages.extend(messages) + return True + + monkeypatch.setattr(execution_jobs, "append_execution_events", fake_append) + writer = execution_jobs.ExecutionEventBatchWriter(flush_interval=0.05, batch_size=1) + writer.start() + try: + writer.enqueue(job_id=1, batch_id="b1", level="info", message="in-flight") + assert first_started.wait(1) + writer.enqueue(job_id=1, batch_id="b1", level="info", message="queued-after") + + # 后台线程仍在写第一批时,flush 必须在 timeout 附近立即返回 False,且不能插队写 queued-after + started_at = time.monotonic() + assert writer.flush(timeout=0.06) is False + elapsed = time.monotonic() - started_at + assert elapsed < 0.25 + assert flushed_messages == [] + + # stop 超时同样立即返回 False,不丢线程与队列引用 + assert writer.stop(timeout=0.05) is False + finally: + gate.set() + assert writer.stop(timeout=2.0) is True + + # 严格按 FIFO 顺序先落第一批,再落队列后续批 + assert flushed_messages == ["in-flight", "queued-after"] + + # 线程未运行时残留事件也按 FIFO 同步排空 + writer.enqueue(job_id=1, batch_id="b1", level="info", message="tail-1") + writer.enqueue(job_id=1, batch_id="b1", level="info", message="tail-2") + assert writer.flush(timeout=0.05) is True + assert flushed_messages == ["in-flight", "queued-after", "tail-1", "tail-2"] + + +def test_execution_worker_error_event_stays_after_step_logs(db, monkeypatch): + user = _user(db, "execution-error-order") + job = enqueue_execution_job( + db, + job_type=JOB_DOUYU_BATCH, + lane_scope=LANE_FULFILLMENT, + batch_id="exec-error-order", + payload={"task_type": "query_points", "payload": {}, "concurrency": 1}, + created_by=int(user.id), + ) + db.commit() + worker = execution_worker.ExecutionJobWorker() + claimed = claim_execution_jobs( + lane_scopes=(LANE_FULFILLMENT,), + owner=worker._owner, + limit=1, + ) + assert [row.id for row in claimed] == [job.id] + + class FailingDouyuRunner: + def __init__(self, **kwargs): + self.log_sink = kwargs["log_sink"] + + def run(self): + self.log_sink({"level": "info", "message": "step-1"}) + self.log_sink({"level": "info", "message": "step-2"}) + raise RuntimeError("boom") + + monkeypatch.setattr(execution_worker, "DouyuBatchRunner", FailingDouyuRunner) + worker._event_writer.start() + try: + worker._run_job(int(job.id)) + finally: + assert worker._event_writer.stop() is True + + db.rollback() + events = execution_events_after(db, batch_id="exec-error-order") + assert [item.message for item in events] == [ + "step-1", + "step-2", + "RuntimeError: boom", + ] + + +def test_resolve_pool_limits_by_runtime_role(monkeypatch): + from web.backend.database import resolve_pool_limits + + monkeypatch.setenv("DB_POOL_SIZE", "20") + monkeypatch.setenv("DB_MAX_OVERFLOW", "20") + monkeypatch.setenv("WORKER_DB_POOL_SIZE", "24") + monkeypatch.setenv("WORKER_DB_MAX_OVERFLOW", "16") + + api_limits = resolve_pool_limits("api") + assert api_limits == { + "api_pool_size": 20, + "api_max_overflow": 20, + "worker_pool_size": 4, + "worker_max_overflow": 4, + } + + bg_limits = resolve_pool_limits("background") + assert bg_limits == { + "api_pool_size": 2, + "api_max_overflow": 2, + "worker_pool_size": 24, + "worker_max_overflow": 16, + } + + all_limits = resolve_pool_limits("all") + assert all_limits == { + "api_pool_size": 20, + "api_max_overflow": 20, + "worker_pool_size": 24, + "worker_max_overflow": 16, + } diff --git a/uv.lock b/uv.lock index d512cdf..7840e9a 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.18" +version = "0.4.21" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/database.py b/web/backend/database.py index a2853a9..3a55009 100644 --- a/web/backend/database.py +++ b/web/backend/database.py @@ -27,6 +27,42 @@ def _pool_mode(name: str, default: str = "queue") -> str: return mode if mode in {"queue", "null"} else default +def resolve_pool_limits(runtime_role: str | None = None) -> dict[str, int]: + """按进程角色拆分主池与后台池上限,避免双进程同配把 MySQL 打满。 + + `BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=true` 时,容器内同时运行 + ``api`` 与 ``background`` 两个进程并共享同一份环境变量: + - ``api`` 进程几乎不跑后台 worker,把 ``worker_engine`` 压到小池; + - ``background`` 进程不接 HTTP 请求,把 ``engine`` 压到小池; + - ``all`` / 未设置(本地调试、单进程、测试)保留完整配置。 + """ + role = ( + runtime_role + if runtime_role is not None + else os.getenv("RUNTIME_ROLE", "all") + ).strip().lower() + api_size = _env_int("DB_POOL_SIZE", 20) + api_overflow = _env_int("DB_MAX_OVERFLOW", 20) + worker_size = _env_int("WORKER_DB_POOL_SIZE", 24) + worker_overflow = _env_int("WORKER_DB_MAX_OVERFLOW", 16) + if role == "api": + worker_size = min(worker_size, _env_int("API_WORKER_DB_POOL_SIZE", 4)) + worker_overflow = min( + worker_overflow, _env_int("API_WORKER_DB_MAX_OVERFLOW", 4) + ) + elif role == "background": + api_size = min(api_size, _env_int("BACKGROUND_DB_POOL_SIZE", 2)) + api_overflow = min( + api_overflow, _env_int("BACKGROUND_DB_MAX_OVERFLOW", 2) + ) + return { + "api_pool_size": api_size, + "api_max_overflow": api_overflow, + "worker_pool_size": worker_size, + "worker_max_overflow": worker_overflow, + } + + def _get_database_url() -> str: """优先使用完整连接串,否则按 DB_* 环境变量构造 MySQL 连接。""" database_url = os.getenv("DATABASE_URL", "").strip() @@ -62,6 +98,8 @@ connect_args = ( else {} ) +_POOL_LIMITS = resolve_pool_limits() + engine_options = { "connect_args": connect_args, "echo": False, @@ -72,8 +110,8 @@ if not DATABASE_URL.startswith("sqlite"): else: engine_options["pool_pre_ping"] = True engine_options.update( - pool_size=_env_int("DB_POOL_SIZE", 20), - max_overflow=_env_int("DB_MAX_OVERFLOW", 20), + pool_size=_POOL_LIMITS["api_pool_size"], + max_overflow=_POOL_LIMITS["api_max_overflow"], pool_timeout=_env_int("DB_POOL_TIMEOUT", 30), pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), ) @@ -96,9 +134,9 @@ if not DATABASE_URL.startswith("sqlite"): else: worker_engine_options["pool_pre_ping"] = True worker_engine_options.update( - pool_size=_env_int("WORKER_DB_POOL_SIZE", 12), - max_overflow=_env_int("WORKER_DB_MAX_OVERFLOW", 4), - pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 30), + pool_size=_POOL_LIMITS["worker_pool_size"], + max_overflow=_POOL_LIMITS["worker_max_overflow"], + pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 60), pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), ) diff --git a/web/backend/services/account_value.py b/web/backend/services/account_value.py index e6bf536..17affd6 100644 --- a/web/backend/services/account_value.py +++ b/web/backend/services/account_value.py @@ -189,12 +189,15 @@ def refresh_account_value_tiers( *, now: datetime | None = None, batch_size: int = 1000, + update_chunk_size: int = 200, ) -> int: - """分批刷新账号价值投影,避免在页面请求里反复执行大 CASE。""" + """分批刷新账号价值投影,先只读筛选变更行再小批量加锁更新。""" moment = now or datetime.now(UTC) batch = max(1, int(batch_size)) + chunk = max(1, int(update_chunk_size)) last_id = 0 changed = 0 + tier = _computed_value_tier_expr(now=moment) while True: account_ids = [ int(row[0]) @@ -208,9 +211,8 @@ def refresh_account_value_tiers( ] if not account_ids: break - tier = _computed_value_tier_expr(now=moment) - changed += int( - db.query(Account) + stale_rows = ( + db.query(Account.id, tier.label("target_tier")) .filter( Account.id.in_(account_ids), or_( @@ -218,10 +220,26 @@ def refresh_account_value_tiers( Account.value_tier != tier, ), ) - .update({Account.value_tier: tier}, synchronize_session=False) - or 0 + .all() ) - db.commit() + if not stale_rows: + db.commit() + last_id = account_ids[-1] + continue + + by_tier: dict[int, list[int]] = {} + for account_id, target_tier in stale_rows: + by_tier.setdefault(int(target_tier), []).append(int(account_id)) + for target_tier, ids in by_tier.items(): + for offset in range(0, len(ids), chunk): + part = ids[offset : offset + chunk] + changed += int( + db.query(Account) + .filter(Account.id.in_(part)) + .update({Account.value_tier: target_tier}, synchronize_session=False) + or 0 + ) + db.commit() last_id = account_ids[-1] return changed diff --git a/web/backend/services/account_work_queue.py b/web/backend/services/account_work_queue.py index 773ed06..c2c4e9c 100644 --- a/web/backend/services/account_work_queue.py +++ b/web/backend/services/account_work_queue.py @@ -26,12 +26,36 @@ def active_account_work_exists(*, work_type: str): .where( AccountWorkItem.account_id == Account.id, AccountWorkItem.work_type == work_type, - AccountWorkItem.status.in_(("pending", "running")), + AccountWorkItem.active_dedupe_key.isnot(None), ) .exists() ) +def active_account_work_ids( + db: Session, + *, + work_type: str, + limit: int = 5000, +) -> tuple[int, ...] | None: + """读取指定类型的在途账号 ID 集合(仅扫 active_dedupe_key 非空行)。 + + 当在途数量超过 ``limit`` 时返回 ``None``,由调用方回退到 SQL 子查询。 + """ + rows = ( + db.query(AccountWorkItem.account_id) + .filter( + AccountWorkItem.active_dedupe_key.isnot(None), + AccountWorkItem.work_type == work_type, + ) + .limit(max(1, int(limit)) + 1) + .all() + ) + if len(rows) > limit: + return None + return tuple(dict.fromkeys(int(account_id) for (account_id,) in rows)) + + def active_account_work_count( db: Session, *, @@ -44,7 +68,7 @@ def active_account_work_count( return 0 query = db.query(func.count(AccountWorkItem.id)).filter( AccountWorkItem.work_type.in_(work_types), - AccountWorkItem.status.in_(("pending", "running")), + AccountWorkItem.active_dedupe_key.isnot(None), ) if reason_prefix: query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%")) @@ -83,29 +107,48 @@ def enqueue_account_work( existing.due_at = due_at db.flush() return existing - item = AccountWorkItem( - account_id=account_id, - work_type=work_type[:32], - priority=int(priority), - # MySQL DATETIME 不保存微秒;立即到期的工作项必须落在当前秒, - # 否则四舍五入到下一秒后,本轮 claim 会误判“还没到期”。 - due_at=(due_at or datetime.now(UTC)).replace(microsecond=0), - max_attempts=max(1, int(max_attempts)), - dedupe_key=dedupe_key[:191], - reason=reason[:255], - payload_json=payload, - ) - try: - with db.begin_nested(): - db.add(item) - db.flush() - return item - except IntegrityError: - return ( - db.query(AccountWorkItem) - .filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191]) - .one() + bind = db.get_bind() + last_exc: IntegrityError | None = None + for _ in range(3): + item = AccountWorkItem( + account_id=account_id, + work_type=work_type[:32], + priority=int(priority), + # MySQL DATETIME 不保存微秒;立即到期的工作项必须落在当前秒, + # 否则四舍五入到下一秒后,本轮 claim 会误判“还没到期”。 + due_at=(due_at or datetime.now(UTC)).replace(microsecond=0), + max_attempts=max(1, int(max_attempts)), + dedupe_key=dedupe_key[:191], + reason=reason[:255], + payload_json=payload, ) + try: + with db.begin_nested(): + db.add(item) + db.flush() + return item + except IntegrityError as exc: + last_exc = exc + existing = ( + db.query(AccountWorkItem) + .filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191]) + .first() + ) + if existing is not None: + return existing + # MySQL REPEATABLE READ 快照看不到并发事务刚提交的行(或对方刚消费完成并 + # 清空 active_dedupe_key),用同 bind 的新只读会话查最新已提交状态。 + with Session(bind=bind) as probe: + existing_latest = ( + probe.query(AccountWorkItem) + .filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191]) + .first() + ) + if existing_latest is not None: + probe.expunge(existing_latest) + return existing_latest + assert last_exc is not None + raise last_exc def claim_account_work( diff --git a/web/backend/services/douyu_runner.py b/web/backend/services/douyu_runner.py index 3d2e11d..d753a00 100644 --- a/web/backend/services/douyu_runner.py +++ b/web/backend/services/douyu_runner.py @@ -238,8 +238,13 @@ class DouyuBatchRunner( self.db.commit() for task in tasks: self._push_task_event(task) + task_ids = [int(task.id) for task in tasks] + # 批次调度阶段后续只等待各任务子槽完成,不再使用外层会话; + # 尽早释放连接,避免阻塞期间白占连接池。 + if getattr(self, "close_db", True): + self.db.close() - total = len(tasks) + total = len(task_ids) lane = douyu_lane_for_task(self.task_type) pending: dict = {} next_index = 0 @@ -249,11 +254,11 @@ class DouyuBatchRunner( and next_index < total and len(pending) < self.concurrency ): - task = tasks[next_index] + task_id = task_ids[next_index] future = submit( lane, self._execute_one, - task.id, + task_id, config, total, stopped=self._stop.is_set, diff --git a/web/backend/services/douyu_runner_core.py b/web/backend/services/douyu_runner_core.py index 2741245..761c8bc 100644 --- a/web/backend/services/douyu_runner_core.py +++ b/web/backend/services/douyu_runner_core.py @@ -130,6 +130,7 @@ class DouyuBatchRunnerCore: self.log_sink = log_sink self._stop = threading.Event() self._counter_lock = threading.Lock() + self._hook_local = threading.local() self._started = 0 # 代理接入 (配置源 = 代理配置页, 与 CK 检测/虎牙注册同款): # 仅兑换/锁单/支付/充值/送礼等写操作任务走代理, 查询/刷新/绑定类直连 @@ -245,25 +246,39 @@ class DouyuBatchRunnerCore: except Exception: # noqa: BLE001 - 日志落库不能中断任务 logger.exception("写入斗鱼任务事件失败: {}", self.batch_id) - def _sync_platform_fulfillment(self, douyu_task_id: int, *, enabled: bool) -> None: + def _sync_platform_fulfillment( + self, + douyu_task_id: int, + *, + enabled: bool, + ) -> None: """绑定/确认任务完成后立即刷新履约投影并写 Outbox。""" if not enabled: return + active_db: Session | None = getattr(self._hook_local, "db", None) + sync_db: Session | None = None try: - from ..database import WorkerSessionLocal from .platform_fulfillment.service import sync_task_from_binding_runner - # 当前批次会话刚刚提交过任务结果。履约投影使用独立短会话,避免 - # get_task_detail 留下的只读事务在下一轮外部 HTTP 轮询期间占连接。 + if active_db is not None: + sync_task_from_binding_runner(active_db, douyu_task_id=int(douyu_task_id)) + return + + from ..database import WorkerSessionLocal + sync_db = WorkerSessionLocal() - try: - sync_task_from_binding_runner(sync_db, douyu_task_id=int(douyu_task_id)) - finally: - sync_db.close() + sync_task_from_binding_runner(sync_db, douyu_task_id=int(douyu_task_id)) except Exception: # noqa: BLE001 - 履约投影失败不能覆盖任务执行结果 + if active_db is not None: + active_db.rollback() + elif sync_db is not None: + sync_db.rollback() logger.exception( "[douyu] 同步直播账号履约状态失败: task_id={}", douyu_task_id ) + finally: + if sync_db is not None: + sync_db.close() def _verify_platform_binding( self, @@ -274,27 +289,39 @@ class DouyuBatchRunnerCore: """确认绑定完成后,再去斗鱼实时查询复核一次。""" if not enabled: return + active_db: Session | None = getattr(self._hook_local, "db", None) + verify_db: Session | None = None try: - from ..database import WorkerSessionLocal - from .platform_fulfillment.service import verify_active_binding_for_douyu_task + from .platform_fulfillment.service import ( + verify_active_binding_for_douyu_task, + ) - verify_db = WorkerSessionLocal() - try: - task = verify_db.get(DouyuTask, int(douyu_task_id)) - if task is None or task.status != "success": - return - verify_active_binding_for_douyu_task( - verify_db, - douyu_task_id=int(douyu_task_id), - actor_id=int(task.created_by), - ) - finally: - verify_db.close() + target_db = active_db + if target_db is None: + from ..database import WorkerSessionLocal + + verify_db = WorkerSessionLocal() + target_db = verify_db + task = target_db.get(DouyuTask, int(douyu_task_id)) + if task is None or task.status != "success": + return + verify_active_binding_for_douyu_task( + target_db, + douyu_task_id=int(douyu_task_id), + actor_id=int(task.created_by), + ) except Exception: # noqa: BLE001 - 复核异常不能覆盖主任务提交 + if active_db is not None: + active_db.rollback() + elif verify_db is not None: + verify_db.rollback() logger.exception( "[douyu] 自动复核直播履约绑定状态失败: task_id={}", douyu_task_id, ) + finally: + if verify_db is not None: + verify_db.close() def _refresh_platform_exchange_eligibility( self, @@ -305,30 +332,40 @@ class DouyuBatchRunnerCore: """账号积分/宝典变化后,自动刷新当前履约任务的兑换投影。""" if not enabled: return + active_db: Session | None = getattr(self._hook_local, "db", None) + refresh_db: Session | None = None try: - from ..database import WorkerSessionLocal from .platform_fulfillment.service import ( refresh_active_exchange_eligibility_for_account, ) - refresh_db = WorkerSessionLocal() - try: - task = refresh_db.get(DouyuTask, int(douyu_task_id)) - if task is None or task.status != "success": - return - refresh_active_exchange_eligibility_for_account( - refresh_db, - account_id=int(task.account_id), - scope=str(task.handbook_scope or "elite"), - actor_id=int(task.created_by), - ) - finally: - refresh_db.close() + target_db = active_db + if target_db is None: + from ..database import WorkerSessionLocal + + refresh_db = WorkerSessionLocal() + target_db = refresh_db + task = target_db.get(DouyuTask, int(douyu_task_id)) + if task is None or task.status != "success": + return + refresh_active_exchange_eligibility_for_account( + target_db, + account_id=int(task.account_id), + scope=str(task.handbook_scope or "elite"), + actor_id=int(task.created_by), + ) except Exception: # noqa: BLE001 - 自动刷新不能覆盖任务执行结果 + if active_db is not None: + active_db.rollback() + elif refresh_db is not None: + refresh_db.rollback() logger.exception( "[douyu] 自动刷新直播履约兑换资格失败: task_id={}", douyu_task_id, ) + finally: + if refresh_db is not None: + refresh_db.close() def _sync_platform_fulfillment_operation( self, @@ -432,21 +469,26 @@ class DouyuBatchRunnerCore: logger.exception( "[douyu] 写入账号任务结果事件失败: task_id={}", task.id ) - self._sync_platform_fulfillment( - task_id, - enabled=sync_platform_fulfillment, - ) - self._verify_platform_binding( - task_id, - enabled=(status == "success" and task.task_type == "confirm_bind"), - ) - self._refresh_platform_exchange_eligibility( - task_id, - enabled=( - status == "success" - and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES - ), - ) + previous_db = getattr(self._hook_local, "db", None) + self._hook_local.db = db + try: + self._sync_platform_fulfillment( + task_id, + enabled=sync_platform_fulfillment, + ) + self._verify_platform_binding( + task_id, + enabled=(status == "success" and task.task_type == "confirm_bind"), + ) + self._refresh_platform_exchange_eligibility( + task_id, + enabled=( + status == "success" + and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES + ), + ) + finally: + self._hook_local.db = previous_db def _schedule_payment_poll( self, @@ -488,7 +530,15 @@ class DouyuBatchRunnerCore: db.commit() self._push_task_event(task) if sync_platform: - self._sync_platform_fulfillment(task_id, enabled=has_platform_task) + previous_db = getattr(self._hook_local, "db", None) + self._hook_local.db = db + try: + self._sync_platform_fulfillment( + task_id, + enabled=has_platform_task, + ) + finally: + self._hook_local.db = previous_db def _upsert_goods(self, db: Session, goods: list[dict]) -> None: upsert_goods_snapshot(db, goods) diff --git a/web/backend/services/execution_jobs.py b/web/backend/services/execution_jobs.py index dc535da..f1c07cb 100644 --- a/web/backend/services/execution_jobs.py +++ b/web/backend/services/execution_jobs.py @@ -4,7 +4,10 @@ from __future__ import annotations import os import socket +import threading +import time import uuid +from collections import deque from datetime import UTC, datetime, timedelta from typing import Any @@ -315,6 +318,34 @@ def get_execution_job( ) +def append_execution_events(events: list[dict[str, Any]]) -> bool: + """批量写入执行任务日志事件,避免高频单条写库占满连接池。""" + if not events: + return True + db = WorkerSessionLocal() + try: + db.add_all( + [ + ExecutionJobEvent( + job_id=int(item["job_id"]), + batch_id=str(item["batch_id"])[:64], + level=str(item.get("level") or "info")[:16], + message=str(item.get("message") or "")[:8000], + payload_json=item.get("payload") or None, + ) + for item in events + ] + ) + db.commit() + return True + except Exception: # noqa: BLE001 - 日志旁路不能中断任务 + db.rollback() + logger.exception("批量写入执行任务事件失败 count={}", len(events)) + return False + finally: + db.close() + + def append_execution_event( *, job_id: int, @@ -323,23 +354,143 @@ def append_execution_event( 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, + append_execution_events( + [ + { + "job_id": int(job_id), + "batch_id": batch_id, + "level": level, + "message": message, + "payload": payload, + } + ] + ) + + +class ExecutionEventBatchWriter: + """后台聚合写入执行事件,严格保持 FIFO 顺序并遵守 flush 超时上限。""" + + def __init__( + self, + *, + flush_interval: float = 0.2, + batch_size: int = 64, + ) -> None: + self._flush_interval = max(0.05, float(flush_interval)) + self._batch_size = max(1, int(batch_size)) + self._cond = threading.Condition() + self._write_lock = threading.Lock() + self._queue: deque[dict[str, Any]] = deque() + self._flushing = False + self._stop = False + self._thread: threading.Thread | None = None + + def start(self) -> None: + with self._cond: + if self._thread is not None and self._thread.is_alive(): + return + self._stop = False + self._thread = threading.Thread( + target=self._run, + name="execution-event-writer", + daemon=True, ) - ) - db.commit() - except Exception: # noqa: BLE001 - 日志旁路不能中断任务 - db.rollback() - logger.exception("写入执行任务事件失败 job_id={}", job_id) - finally: - db.close() + self._thread.start() + + def is_running(self) -> bool: + with self._cond: + return self._thread is not None and self._thread.is_alive() + + def _drain_sync(self) -> bool: + """在后台线程未运行时按 FIFO 同步写完队列中剩余事件。""" + with self._write_lock: + with self._cond: + remaining = list(self._queue) + self._queue.clear() + if not remaining: + return True + return append_execution_events(remaining) + + def stop(self, timeout: float = 5.0) -> bool: + with self._cond: + self._stop = True + self._cond.notify_all() + thread = self._thread + if thread is not None and thread.is_alive(): + thread.join(timeout=max(0.05, float(timeout))) + with self._cond: + still_alive = thread is not None and thread.is_alive() + if not still_alive: + self._thread = None + if still_alive: + # 后台线程仍在写库:保留线程与队列交由它按 FIFO 继续排空,不插队也不丢引用 + return False + return self._drain_sync() + + def enqueue( + self, + *, + job_id: int, + batch_id: str, + level: str, + message: str = "", + payload: dict[str, Any] | None = None, + ) -> None: + item = { + "job_id": int(job_id), + "batch_id": batch_id, + "level": level, + "message": message, + "payload": payload, + } + with self._cond: + if self._thread is not None and self._thread.is_alive(): + self._queue.append(item) + if len(self._queue) >= self._batch_size: + self._cond.notify_all() + return + self._queue.append(item) + self._drain_sync() + + def flush(self, timeout: float = 5.0) -> bool: + deadline = time.monotonic() + max(0.05, float(timeout)) + with self._cond: + thread = self._thread + if thread is None or not thread.is_alive(): + need_sync = bool(self._queue) + self._thread = None + else: + need_sync = False + self._cond.notify_all() + while self._queue or self._flushing: + left = deadline - time.monotonic() + if left <= 0: + return False + self._cond.wait(timeout=min(left, 0.05)) + return True + if need_sync: + return self._drain_sync() + return True + + def _run(self) -> None: + while True: + batch: list[dict[str, Any]] = [] + with self._cond: + while not self._queue and not self._stop: + self._cond.wait(timeout=self._flush_interval) + if not self._queue and self._stop: + self._cond.notify_all() + return + while self._queue and len(batch) < self._batch_size: + batch.append(self._queue.popleft()) + self._flushing = True + try: + with self._write_lock: + append_execution_events(batch) + finally: + with self._cond: + self._flushing = False + self._cond.notify_all() def execution_events_after( @@ -380,7 +531,9 @@ __all__ = [ "STATUS_QUEUED", "STATUS_RUNNING", "STATUS_SUCCEEDED", + "ExecutionEventBatchWriter", "append_execution_event", + "append_execution_events", "claim_execution_jobs", "enqueue_execution_job", "event_payload", diff --git a/web/backend/services/execution_worker.py b/web/backend/services/execution_worker.py index 4e34026..265ef7e 100644 --- a/web/backend/services/execution_worker.py +++ b/web/backend/services/execution_worker.py @@ -23,7 +23,7 @@ from .execution_jobs import ( LANE_FULFILLMENT, STATUS_CANCELLED, STATUS_SUCCEEDED, - append_execution_event, + ExecutionEventBatchWriter, claim_execution_jobs, execution_worker_owner, fail_execution_job, @@ -99,12 +99,14 @@ class ExecutionJobWorker: self._executors: dict[str, ThreadPoolExecutor] = {} self._inflight: dict[str, int] = {} self._owner = execution_worker_owner() + self._event_writer = ExecutionEventBatchWriter() def start(self) -> bool: with self._lock: if self._thread is not None and self._thread.is_alive(): return False self._stop.clear() + self._event_writer.start() lane_limits = _lane_slot_limits() self._executors = { lane: ThreadPoolExecutor( @@ -142,6 +144,8 @@ class ExecutionJobWorker: thread.join(timeout=5) for executor in executors: executor.shutdown(wait=True, cancel_futures=True) + if not self._event_writer.stop(): + logger.warning("执行任务事件写入线程停机超时,仍有事件等待排空") def _run(self) -> None: futures: dict[Future, str] = {} @@ -214,18 +218,24 @@ class ExecutionJobWorker: job = db.get(ExecutionJob, int(job_id)) if job is None or job.status != "running": return + current_job_id = int(job.id) + current_batch_id = str(job.batch_id) + current_job_type = str(job.job_type) + current_attempt_count = int(job.attempt_count or 0) + current_created_by = int(job.created_by) payload = dict(job.payload_json or {}) - user = db.get(User, int(job.created_by)) + user = db.get(User, current_created_by) if user is None: raise RuntimeError("执行任务创建人不存在") + creator_permissions = get_user_permissions(user) 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, + self._event_writer.enqueue( + job_id=current_job_id, + batch_id=current_batch_id, level=level, message=message, payload=event_payload or None, @@ -239,7 +249,7 @@ class ExecutionJobWorker: runner.stop() return held, cancel_requested = heartbeat_execution_job( - job_id=int(job.id), + job_id=current_job_id, owner=self._owner, ) if not held: @@ -258,20 +268,20 @@ class ExecutionJobWorker: heartbeat = threading.Thread( target=heartbeat_loop, - name=f"execution-heartbeat-{job.id}", + name=f"execution-heartbeat-{current_job_id}", daemon=True, ) heartbeat.start() summary: dict[str, Any] = {} - if job.job_type in {JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH}: + if current_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), + created_by=current_created_by, + creator_permissions=creator_permissions, 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, @@ -283,16 +293,16 @@ class ExecutionJobWorker: trigger_source=str( payload.get("trigger_source", "manual") or "manual" ), - batch_id=job.batch_id, + batch_id=current_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: + elif current_job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}: + if current_attempt_count > 1: # 进程中断会留下 pending/running 的初始任务;支付轮询有独立 # queue_lane,不能被重放。重试只重置尚无后置 lane 的行。 db.query(DouyuTask).filter( - DouyuTask.batch_id == job.batch_id, + DouyuTask.batch_id == current_batch_id, DouyuTask.status.in_(("planned", "pending", "running")), DouyuTask.queue_lane == "", ).update( @@ -305,27 +315,32 @@ class ExecutionJobWorker: db.commit() runner = DouyuBatchRunner( db=db, - batch_id=job.batch_id, + batch_id=current_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, + close_db=True, log_sink=log_sink, ) runner.run() else: - raise RuntimeError(f"不支持的执行任务类型: {job.job_type}") + raise RuntimeError(f"不支持的执行任务类型: {current_job_type}") + if not self._event_writer.flush(): + logger.error( + "执行任务事件落库未在超时内全部确认 job_id={}", + current_job_id, + ) summary = {"finished_at": datetime.now(UTC).isoformat()} held, cancel_requested = heartbeat_execution_job( - job_id=int(job.id), + job_id=current_job_id, owner=self._owner, ) if not held: return finish_execution_job( - job_id=int(job.id), + job_id=current_job_id, owner=self._owner, status=( STATUS_CANCELLED @@ -336,12 +351,17 @@ class ExecutionJobWorker: ) except Exception as exc: # noqa: BLE001 - job 边界必须收口 logger.exception("执行任务失败 job_id={}", job_id) - append_execution_event( + self._event_writer.enqueue( job_id=int(job_id), - batch_id=str(job.batch_id) if job is not None else "", + batch_id=current_batch_id if "current_batch_id" in locals() else "", level="error", message=f"{type(exc).__name__}: {exc}", ) + if not self._event_writer.flush(): + logger.error( + "失败收尾阶段执行任务事件落库未全部确认 job_id={}", + job_id, + ) fail_execution_job( job_id=int(job_id), owner=self._owner, diff --git a/web/backend/services/login_service.py b/web/backend/services/login_service.py index 38bee33..4166ea1 100644 --- a/web/backend/services/login_service.py +++ b/web/backend/services/login_service.py @@ -1124,6 +1124,9 @@ class LoginBatchRunner: _append_task_info(task, acc) self.db.commit() + # 后续阶段只通过 TaskLane.LOGIN 的独立 worker_db 执行,外层协调会话 + # 若不先释放会在等邮箱验证码期间空占连接池长达 25 分钟。 + self.db.close() total = len(task_infos) if total == 0: self._push_log("warning", "没有可执行的账号") diff --git a/web/backend/services/platform_fulfillment/account_selector.py b/web/backend/services/platform_fulfillment/account_selector.py index 1e2d2c3..c64975f 100644 --- a/web/backend/services/platform_fulfillment/account_selector.py +++ b/web/backend/services/platform_fulfillment/account_selector.py @@ -10,7 +10,7 @@ from dataclasses import dataclass from datetime import UTC, datetime, timedelta from typing import Any -from sqlalchemy import and_, case, literal, or_, select +from sqlalchemy import and_, case, func, literal, or_, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session, aliased @@ -39,7 +39,7 @@ from ..account_query_filters import ( valid_ck_filter, ) from ..account_sync_runner import WORK_STOREHOME_SYNC -from ..account_work_queue import active_account_work_exists +from ..account_work_queue import active_account_work_exists, active_account_work_ids from .policy import ( PRIORITY_KEY_BUNDLE_MATCH, PRIORITY_KEY_CK_FRESHNESS, @@ -666,52 +666,65 @@ def capability_refresh_candidate_accounts( ) .exists() ) - refresh_needed = [] - for commodity_id in commodities: - state_exists = ( - select(AccountCommodityState.id) - .where( - AccountCommodityState.account_id == Account.id, - AccountCommodityState.platform == "douyu", - AccountCommodityState.scope == scope, - AccountCommodityState.commodity_id == commodity_id, - ) - .exists() - ) - state_due = ( - select(AccountCommodityState.id) - .where( - AccountCommodityState.account_id == Account.id, - AccountCommodityState.platform == "douyu", - AccountCommodityState.scope == scope, - AccountCommodityState.commodity_id == commodity_id, - or_( - AccountCommodityState.valid_until.is_(None), - AccountCommodityState.valid_until <= moment, - AccountCommodityState.next_check_at.is_(None), - AccountCommodityState.next_check_at <= moment, - ), - ) - .exists() - ) - refresh_needed.append( + state_due = ( + select(AccountCommodityState.id) + .where( + AccountCommodityState.account_id == Account.id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id.in_(commodities), or_( - and_(~fresh_storehome, ~state_exists), - state_due, + AccountCommodityState.valid_until.is_(None), + AccountCommodityState.valid_until <= moment, + AccountCommodityState.next_check_at.is_(None), + AccountCommodityState.next_check_at <= moment, + ), + ) + .exists() + ) + if len(commodities) == 1: + missing_state = ~( + select(AccountCommodityState.id) + .where( + AccountCommodityState.account_id == Account.id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id == commodities[0], ) + .exists() + ) + else: + # (account_id, platform, scope, commodity_id) 有唯一约束 uq_account_commodity_state, + # 行数少于待履约商品数即表示至少缺失一个商品的快照行。 + missing_state = ( + select(func.count(AccountCommodityState.id)) + .where( + AccountCommodityState.account_id == Account.id, + AccountCommodityState.platform == "douyu", + AccountCommodityState.scope == scope, + AccountCommodityState.commodity_id.in_(commodities), + ) + .scalar_subquery() + < len(commodities) ) + query = db.query(Account).filter( + or_( + state_due, + and_(~fresh_storehome, missing_state), + ), + cookie_present_filter(), + valid_ck_filter(), + automatable_account_filter(), + assigned_to_pool_filter(), + ) + active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC) + if active_work_ids is None: + query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC)) + elif active_work_ids: + query = query.filter(~Account.id.in_(active_work_ids)) return ( - db.query(Account) - .filter( - or_(*refresh_needed), - cookie_present_filter(), - valid_ck_filter(), - automatable_account_filter(), - assigned_to_pool_filter(), - ~active_account_work_exists(work_type=WORK_STOREHOME_SYNC), - ) - .order_by(*_refresh_candidate_order_by(moment)) + query.order_by(*_refresh_candidate_order_by(moment)) .limit(max(1, min(int(limit), 100))) .all() ) @@ -791,8 +804,12 @@ def storehome_refresh_candidate_accounts( valid_ck_filter(), automatable_account_filter(), assigned_to_pool_filter(), - ~active_account_work_exists(work_type=WORK_STOREHOME_SYNC), ) + active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC) + if active_work_ids is None: + query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC)) + elif active_work_ids: + query = query.filter(~Account.id.in_(active_work_ids)) if excluded_ids: query = query.filter(~Account.id.in_(excluded_ids)) order_by: list[Any] = []