diff --git a/README.md b/README.md index 4e284ce..c2e2821 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 直播账号运营后台 -斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.22)。 +斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.23)。 ## 能做什么 diff --git a/core/douyu/activity_client.py b/core/douyu/activity_client.py index 7e58414..3479628 100644 --- a/core/douyu/activity_client.py +++ b/core/douyu/activity_client.py @@ -7,7 +7,7 @@ import re import secrets import time from collections.abc import Callable -from typing import Any, cast +from typing import Any, Self, cast from urllib.parse import parse_qs, unquote, urlsplit, urlunsplit import requests @@ -2319,3 +2319,17 @@ class DouyuActivityClient: "new_balance": self._xpd_int(info.get("newBalance")), "raw": info, } + + def close(self) -> None: + """关闭底层 HTTP 会话,释放连接池。""" + session = getattr(self, "session", None) + if session is not None: + close = getattr(session, "close", None) + if callable(close): + close() + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_exc: object) -> None: + self.close() diff --git a/core/douyu/email_verifier.py b/core/douyu/email_verifier.py index c0e1773..63d6a33 100644 --- a/core/douyu/email_verifier.py +++ b/core/douyu/email_verifier.py @@ -6,6 +6,7 @@ import re import threading import time from datetime import UTC, datetime, timedelta +from typing import Self import requests from loguru import logger @@ -61,17 +62,32 @@ class EmailVerifier: """兼容接口""" def disconnect(self) -> None: - """关闭 Roundcube 会话""" - if self._rc_session: + """关闭 Roundcube 会话并释放 HTTP 连接池""" + session = self._rc_session + self._rc_session = None + self._rc_token = None + self._rc_logged_in = False + if session is not None: try: - self._rc_session.get( + session.get( f"{self.roundcube_url}?_task=logout", timeout=5, ) except Exception as exc: # noqa: BLE001 logger.debug(f"Roundcube logout failed: {exc}") - self._rc_session = None - self._rc_logged_in = False + finally: + close = getattr(session, "close", None) + if callable(close): + close() + + def close(self) -> None: + self.disconnect() + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_exc: object) -> None: + self.disconnect() # ── Roundcube 会话管理 ────────────────────────────────── @@ -117,8 +133,10 @@ class EmailVerifier: self, password: str, is_backup: bool = False ) -> tuple[bool, bool]: """尝试一次 Roundcube 登录,返回 (是否成功, 是否明确为密码错误)。""" + session = requests.Session() + session.trust_env = False + adopted = False try: - session = requests.Session() session.headers.update( { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36", @@ -169,7 +187,13 @@ class EmailVerifier: logger.warning(f"Roundcube: {password_name}登录失败") return False, True + old_session = self._rc_session self._rc_session = session + adopted = True + if old_session is not None and old_session is not session: + close = getattr(old_session, "close", None) + if callable(close): + close() self._rc_token = new_token_match.group(1) self._rc_logged_in = True password_name = "备用邮箱密码" if is_backup else "主邮箱密码" @@ -179,6 +203,11 @@ class EmailVerifier: except Exception as e: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 logger.warning(f"Roundcube: 登录异常: {e}") return False, False + finally: + if not adopted: + close = getattr(session, "close", None) + if callable(close): + close() # ── Roundcube 邮件列表(含精确日期) ──────────────────── diff --git a/core/douyu/login.py b/core/douyu/login.py index cff535a..db17464 100644 --- a/core/douyu/login.py +++ b/core/douyu/login.py @@ -6,7 +6,7 @@ import re import threading import time from collections.abc import Mapping -from typing import Protocol +from typing import Protocol, Self from urllib.parse import urlsplit, urlunsplit import requests @@ -165,6 +165,20 @@ class DouyuLogin: self._email_channel_switched = False self._setup_session() + def close(self) -> None: + """关闭登录 HTTP 会话。""" + session = getattr(self, "session", None) + if session is not None: + close = getattr(session, "close", None) + if callable(close): + close() + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_exc: object) -> None: + self.close() + def _is_stopped(self) -> bool: """判断外部批量任务是否请求停止。""" return bool(self.stop_event and self.stop_event.is_set()) @@ -376,22 +390,27 @@ class DouyuLogin: # 发信前先记录收件箱里最新的斗鱼邮件 UID:之后只认比它更新的邮件, # 才能确保取到的是「本次发送触发的那封」,而不是上一轮残留的旧验证码。 verifier = self._create_email_verifier() - baseline_uid = verifier.latest_douyu_uid() - logger.info(f"步骤4: 发信前最新斗鱼邮件 UID={baseline_uid}") - email_sent_at = time.time() - self._send_email_verify(value) + try: + baseline_uid = verifier.latest_douyu_uid() + logger.info(f"步骤4: 发信前最新斗鱼邮件 UID={baseline_uid}") + email_sent_at = time.time() + self._send_email_verify(value) - # 5️⃣ 等待邮箱验证码 - logger.info( - f"步骤5: 获取邮箱验证码(通道 {self.api.name}," - f"最多等 {self._email_code_wait_seconds()}s)..." - ) - verify_code = self._wait_for_email_code( - verifier, - baseline_uid=baseline_uid, - email_sent_at=email_sent_at, - deadline=deadline, - ) + # 5️⃣ 等待邮箱验证码 + logger.info( + f"步骤5: 获取邮箱验证码(通道 {self.api.name}," + f"最多等 {self._email_code_wait_seconds()}s)..." + ) + verify_code = self._wait_for_email_code( + verifier, + baseline_uid=baseline_uid, + email_sent_at=email_sent_at, + deadline=deadline, + ) + finally: + disconnect = getattr(verifier, "disconnect", None) + if callable(disconnect): + disconnect() # 6️⃣ 提交验证码 logger.info("步骤6: 提交验证码...") diff --git a/core/douyu/proxy_platforms/base.py b/core/douyu/proxy_platforms/base.py index 68fa21a..e222d96 100644 --- a/core/douyu/proxy_platforms/base.py +++ b/core/douyu/proxy_platforms/base.py @@ -155,19 +155,21 @@ def _get_local_exit_ip() -> str | None: "https://4.ipw.cn", "https://api.ipify.org", ] - for url in targets: - try: - response = requests.get( - url, timeout=8, headers={"User-Agent": "Mozilla/5.0"} - ) - response.raise_for_status() - text = response.text.strip() - match = re.search(r"(\d{1,3}(?:\.\d{1,3}){3})", text) - if match: - return match.group(1) - except Exception as exc: # noqa: BLE001 - logger.debug(f"本机出口 IP 查询失败: {url}: {exc}") - continue + with requests.Session() as sess: + sess.trust_env = False + for url in targets: + try: + with sess.get( + url, timeout=8, headers={"User-Agent": "Mozilla/5.0"} + ) as response: + response.raise_for_status() + text = response.text.strip() + match = re.search(r"(\d{1,3}(?:\.\d{1,3}){3})", text) + if match: + return match.group(1) + except Exception as exc: # noqa: BLE001 + logger.debug(f"本机出口 IP 查询失败: {url}: {exc}") + continue return None @@ -179,26 +181,28 @@ def get_exit_ip_via_proxy(proxy: str) -> str | None: "https://4.ipw.cn", ] proxies = {"http": proxy, "https": proxy} - for url in targets: - try: - response = requests.get( - url, - proxies=proxies, - timeout=6, - headers={"User-Agent": "Mozilla/5.0"}, - ) - response.raise_for_status() - content_type = response.headers.get("content-type", "").lower() - if "json" in content_type: - data = response.json() - ip = data.get("ip") or data.get("origin") - if ip: - return str(ip).split(",")[0].strip() - text = response.text.strip() - match = re.search(r"(\d{1,3}(?:\.\d{1,3}){3})", text) - if match: - return match.group(1) - except Exception as exc: # noqa: BLE001 - logger.debug(f"代理出口 IP 查询失败: {url}: {exc}") - continue + with requests.Session() as sess: + sess.trust_env = False + for url in targets: + try: + with sess.get( + url, + proxies=proxies, + timeout=6, + headers={"User-Agent": "Mozilla/5.0"}, + ) as response: + response.raise_for_status() + content_type = response.headers.get("content-type", "").lower() + if "json" in content_type: + data = response.json() + ip = data.get("ip") or data.get("origin") + if ip: + return str(ip).split(",")[0].strip() + text = response.text.strip() + match = re.search(r"(\d{1,3}(?:\.\d{1,3}){3})", text) + if match: + return match.group(1) + except Exception as exc: # noqa: BLE001 + logger.debug(f"代理出口 IP 查询失败: {url}: {exc}") + continue return None diff --git a/core/douyu/proxy_platforms/xiequ.py b/core/douyu/proxy_platforms/xiequ.py index db6cc6b..6229583 100644 --- a/core/douyu/proxy_platforms/xiequ.py +++ b/core/douyu/proxy_platforms/xiequ.py @@ -52,10 +52,11 @@ class XiequAdapter(BaseWhitelistAdapter): """ try: url = self._build_url(act="getjson") - response = requests.get(url, timeout=10) - response.raise_for_status() - - text = response.text.strip() + with requests.Session() as sess: + sess.trust_env = False + with sess.get(url, timeout=10) as response: + response.raise_for_status() + text = response.text.strip() if not text or text == "[]": return [] @@ -83,10 +84,11 @@ class XiequAdapter(BaseWhitelistAdapter): """添加IP到白名单。""" try: url = self._build_url(act="add", ip=ip, meno=self.memo) - response = requests.get(url, timeout=10) - response.raise_for_status() - - text = response.text.strip() + with requests.Session() as sess: + sess.trust_env = False + with sess.get(url, timeout=10) as response: + response.raise_for_status() + text = response.text.strip() logger.debug(f"添加白名单响应: {text}") if "ok" in text.lower() or "success" in text.lower() or "添加成功" in text: @@ -128,10 +130,11 @@ class XiequAdapter(BaseWhitelistAdapter): """删除白名单IP。""" try: url = self._build_url(act="del", ip=ip) - response = requests.get(url, timeout=10) - response.raise_for_status() - - text = response.text.strip() + with requests.Session() as sess: + sess.trust_env = False + with sess.get(url, timeout=10) as response: + response.raise_for_status() + text = response.text.strip() logger.debug(f"删除白名单响应: {text}") if "ok" in text.lower() or "success" in text.lower() or "删除成功" in text: diff --git a/core/douyu/proxy_platforms/xkdaili.py b/core/douyu/proxy_platforms/xkdaili.py index b53addd..98a3973 100644 --- a/core/douyu/proxy_platforms/xkdaili.py +++ b/core/douyu/proxy_platforms/xkdaili.py @@ -102,10 +102,11 @@ class XkdailiAdapter(BaseWhitelistAdapter): """添加IP到白名单。多个IP用英文逗号隔开。""" try: url = self._build_url(type="addwhiteip", ip=ip) - response = requests.get(url, timeout=10) - response.raise_for_status() - - text = response.text.strip() + with requests.Session() as sess: + sess.trust_env = False + with sess.get(url, timeout=10) as response: + response.raise_for_status() + text = response.text.strip() logger.debug(f"星空添加白名单响应: {text}") ok, msg = self._parse_response(text) @@ -123,10 +124,11 @@ class XkdailiAdapter(BaseWhitelistAdapter): """删除白名单IP。多个IP用英文逗号隔开。""" try: url = self._build_url(type="delwhiteip", ip=ip) - response = requests.get(url, timeout=10) - response.raise_for_status() - - text = response.text.strip() + with requests.Session() as sess: + sess.trust_env = False + with sess.get(url, timeout=10) as response: + response.raise_for_status() + text = response.text.strip() logger.debug(f"星空删除白名单响应: {text}") ok, msg = self._parse_response(text) @@ -145,10 +147,11 @@ class XkdailiAdapter(BaseWhitelistAdapter): try: # 尝试添加无效IP来验证认证 url = self._build_url(type="addwhiteip", ip="0.0.0.0") - response = requests.get(url, timeout=10) - response.raise_for_status() - - text = response.text.strip() + with requests.Session() as sess: + sess.trust_env = False + with sess.get(url, timeout=10) as response: + response.raise_for_status() + text = response.text.strip() ok, msg = self._parse_response(text) if ok: diff --git a/core/douyu/proxy_resolver.py b/core/douyu/proxy_resolver.py index 28b6295..30f62cc 100644 --- a/core/douyu/proxy_resolver.py +++ b/core/douyu/proxy_resolver.py @@ -122,9 +122,11 @@ class ProxyResolver: self._log("info", f"代理预检 {attempt}/{max_attempts}: 正在获取代理") try: - response = requests.get(self.api_url, timeout=10) - response.raise_for_status() - text = response.text.strip() + with requests.Session() as sess: + sess.trust_env = False + with sess.get(self.api_url, timeout=10) as response: + response.raise_for_status() + text = response.text.strip() proxy_urls, whitelist_ip = parse_proxy_response(text) diff --git a/core/douyu/proxy_verifier.py b/core/douyu/proxy_verifier.py index 9f2affc..f548fba 100644 --- a/core/douyu/proxy_verifier.py +++ b/core/douyu/proxy_verifier.py @@ -19,14 +19,16 @@ def verify_proxy_url(proxy_url: str, timeout: tuple = (3, 5)) -> tuple[bool, str # ── 斗鱼主站可达性验证 ── try: - response = requests.get( - "https://www.douyu.com", - proxies=proxies, - timeout=timeout, - headers={"User-Agent": "Mozilla/5.0"}, - ) - response.raise_for_status() - return True, "代理可用 → 斗鱼可达" + with requests.Session() as sess: + sess.trust_env = False + with sess.get( + "https://www.douyu.com", + proxies=proxies, + timeout=timeout, + headers={"User-Agent": "Mozilla/5.0"}, + ) as response: + response.raise_for_status() + return True, "代理可用 → 斗鱼可达" except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 err_msg = str(exc) if "Tunnel connection failed" in err_msg or "503" in err_msg: @@ -63,13 +65,12 @@ def verify_proxies_concurrent( if return_all: available: list[str] = [] - with ThreadPoolExecutor( - max_workers=min(max_workers, len(proxy_urls)) - ) as executor: - future_map = { - executor.submit(verify_proxy_url, proxy, timeout): proxy - for proxy in proxy_urls - } + executor = ThreadPoolExecutor(max_workers=min(max_workers, len(proxy_urls))) + future_map = { + executor.submit(verify_proxy_url, proxy, timeout): proxy + for proxy in proxy_urls + } + try: for future in as_completed(future_map): try: ok, _ = future.result() @@ -78,6 +79,8 @@ def verify_proxies_concurrent( except Exception as exc: # noqa: BLE001 logger.debug(f"代理并发验证失败: {future_map[future]}: {exc}") continue + finally: + executor.shutdown(wait=True, cancel_futures=True) if available: logger.success( f"并发验证找到 {len(available)}/{len(proxy_urls)} 个可用代理" @@ -85,11 +88,12 @@ def verify_proxies_concurrent( return available, f"找到 {len(available)} 个可用代理" return None, f"共 {len(proxy_urls)} 个代理均不可用" - with ThreadPoolExecutor(max_workers=min(max_workers, len(proxy_urls))) as executor: - future_map = { - executor.submit(verify_proxy_url, proxy, timeout): proxy - for proxy in proxy_urls - } + executor = ThreadPoolExecutor(max_workers=min(max_workers, len(proxy_urls))) + future_map = { + executor.submit(verify_proxy_url, proxy, timeout): proxy + for proxy in proxy_urls + } + try: for future in as_completed(future_map): proxy_url = future_map[future] try: @@ -103,5 +107,8 @@ def verify_proxies_concurrent( except Exception as exc: # noqa: BLE001 logger.debug(f"代理并发验证失败: {proxy_url}: {exc}") continue + finally: + # 命中首个可用代理后立即返回,不能在 with 退出时 wait=True 等慢/挂死代理超时。 + executor.shutdown(wait=False, cancel_futures=True) return None, f"共 {len(proxy_urls)} 个代理均不可用" diff --git a/core/douyu/recharge_api.py b/core/douyu/recharge_api.py index 0df75d6..658c48c 100644 --- a/core/douyu/recharge_api.py +++ b/core/douyu/recharge_api.py @@ -9,7 +9,7 @@ import time from collections.abc import Callable, Mapping from dataclasses import dataclass from decimal import Decimal, InvalidOperation -from typing import Any +from typing import Any, Self import requests @@ -80,6 +80,7 @@ class FishFinRechargeClient: ): config.validate() self.config = config + self._owns_session = session is None self.session = session or requests.Session() self.session.trust_env = False self.trace = trace or (lambda _event: None) @@ -318,3 +319,16 @@ class FishFinRechargeClient: def account_info(self) -> dict[str, Any]: """查询商户账户信息。""" return self._request("GET", self.USER_INFO_PATH) + + def close(self) -> None: + """关闭自建 HTTP 会话,释放连接池。""" + if getattr(self, "_owns_session", False): + close = getattr(self.session, "close", None) + if callable(close): + close() + + def __enter__(self) -> Self: + return self + + def __exit__(self, *_exc: object) -> None: + self.close() diff --git a/pyproject.toml b/pyproject.toml index 51598a6..e78b8ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "live-hub-py" -version = "0.4.22" +version = "0.4.23" description = "直播账号运营 Web 后台" readme = "README.md" requires-python = ">=3.12,<3.13" diff --git a/tests/test_douyu_p0_p1_fixes.py b/tests/test_douyu_p0_p1_fixes.py new file mode 100644 index 0000000..ba78562 --- /dev/null +++ b/tests/test_douyu_p0_p1_fixes.py @@ -0,0 +1,391 @@ +"""斗鱼相关 P0 + P1 修复回归测试。""" + +from __future__ import annotations + +import threading +import time +from concurrent.futures import Future +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest +from sqlalchemy import inspect + +from core.douyu import DouyuActivityClient, FishFinRechargeClient, FishFinRechargeConfig +from core.douyu.email_verifier import EmailVerifier +from core.douyu.login import DouyuLogin +from core.douyu.proxy_verifier import verify_proxies_concurrent +from tests.support.db import get_test_engine, init_test_schema, make_test_session +from web.backend.database import release_idle_session +from web.backend.models import ( + Account, + AccountSyncRun, + AccountSyncState, + DouyuTask, + PlatformFulfillmentTask, + User, +) +from web.backend.services import account_sync_service +from web.backend.services.douyu_runner import DouyuBatchRunner +from web.backend.services.task_runtime import TaskLane + + +class _TestBase: + def setup_method(self): + self.engine = get_test_engine() + init_test_schema(self.engine) + self.session = make_test_session(self.engine) + self.user = User(username="p0p1-admin", password_hash="h", role="super_admin") + self.session.add(self.user) + self.session.flush() + self.account = Account( + username="p0p1-acc", + password="p", + email="p0p1@example.com", + email_password="ep", + uid="10086", + cookie="acf_uid=10086; acf_ltkid=1; acf_username=u", + ) + self.session.add(self.account) + self.session.commit() + self.account_id = int(self.account.id) + self.user_id = int(self.user.id) + + def teardown_method(self): + self.session.close() + + +class TestLockOrderAndSingleWriteSync(_TestBase): + def test_record_sync_success_locks_account_and_inserts_single_finished_run(self): + events: list[str] = [] + original_lock = account_sync_service.lock_account_row + + def spy_lock(db, account_id): + events.append(f"lock:{account_id}") + return original_lock(db, account_id) + + observed_at = datetime.now(UTC) + with patch.object(account_sync_service, "lock_account_row", side_effect=spy_lock): + run = account_sync_service.record_sync_success( + self.session, + account_id=self.account_id, + domain="points", + source="test.sync", + observed_at=observed_at, + raw_payload={"points": 1200}, + task_id=42, + ) + self.session.commit() + + assert events == [f"lock:{self.account_id}"] + assert run.observed_at == observed_at + runs = ( + self.session.query(AccountSyncRun) + .filter(AccountSyncRun.account_id == self.account_id) + .all() + ) + assert len(runs) == 1 + assert runs[0].status == "success" + assert runs[0].finished_at is not None + state = ( + self.session.query(AccountSyncState) + .filter( + AccountSyncState.account_id == self.account_id, + AccountSyncState.domain == "points", + ) + .one() + ) + assert state.status == "success" + + +class TestSessionReleaseAndClientLifecycle(_TestBase): + def test_release_idle_session_respects_managed_and_dirty_flags(self): + # Unmanaged test session must never be rolled back. + assert release_idle_session(self.session) is False + + # Dirty managed session must not drop pending changes. + self.session.info["managed_worker_session"] = True + self.account.nickname = "dirty-check" + assert release_idle_session(self.session) is False + self.session.rollback() + + # Clean managed session gets rolled back (connection returned to pool). + self.session.info["managed_request_session"] = True + assert release_idle_session(self.session) is True + + def test_runner_releases_preflight_db_and_closes_tracked_clients(self): + task = DouyuTask( + batch_id="b-session-rel", + account_id=self.account_id, + task_type="query_points", + handbook_scope="elite", + status="pending", + created_by=self.user_id, + ) + self.session.add(task) + self.session.commit() + task_id = int(task.id) + + closed_clients: list[DouyuActivityClient] = [] + + class _SpyClient(DouyuActivityClient): + def close(self) -> None: + closed_clients.append(self) + super().close() + + preflight_db = make_test_session(self.engine) + worker_db = make_test_session(self.engine) + close_flags: list[bool] = [] + original_preflight_close = preflight_db.close + original_worker_close = worker_db.close + + def track_preflight_close(): + close_flags.append(True) + original_preflight_close() + + def track_worker_close(): + original_worker_close() + + preflight_db.close = track_preflight_close # type: ignore[method-assign] + worker_db.close = track_worker_close # type: ignore[method-assign] + session_iter = iter([preflight_db, worker_db]) + + def fake_probe_session(cookie: str, *, checker=None): + # Preflight DB must already be closed before external HTTP cookie check runs. + assert close_flags == [True] + return {"status": "valid", "message": "ok", "detail": {"nickname": "n"}} + + runner = DouyuBatchRunner( + self.session, "b-session-rel", "query_points", close_db=False + ) + + def fake_handler(db, t, acc, cookie, cfg): + client = runner._client(cookie) + assert isinstance(client, _SpyClient) + runner._mark_task(db, t, "success", "完成") + + with ( + patch( + "web.backend.services.douyu_runner.SessionLocal", + side_effect=lambda: next(session_iter), + ), + patch( + "web.backend.services.douyu_runner.probe_session", + side_effect=fake_probe_session, + ), + patch( + "web.backend.services.douyu_runner_core.activity_client", + side_effect=lambda c, **_kw: _SpyClient(c), + ), + patch.object(runner, "_execute_query_points", side_effect=fake_handler), + ): + runner._execute_one_with_slot(task_id, {"manual_id": "1"}, 1) + + assert len(closed_clients) == 1 + + +class TestRunnerQueueWaitAndTaskId(_TestBase): + def test_run_logs_true_queue_wait_and_correct_task_id(self): + t1 = DouyuTask( + batch_id="b-queue-wait", + account_id=self.account_id, + task_type="query_points", + handbook_scope="elite", + status="planned", + created_by=self.user_id, + ) + t2 = DouyuTask( + batch_id="b-queue-wait", + account_id=self.account_id, + task_type="query_points", + handbook_scope="elite", + status="planned", + created_by=self.user_id, + ) + self.session.add_all([t1, t2]) + self.session.commit() + id1, id2 = int(t1.id), int(t2.id) + + runner = DouyuBatchRunner( + self.session, + "b-queue-wait", + "query_points", + concurrency=2, + close_db=False, + ) + logs: list[tuple[str, str]] = [] + runner._push_log = lambda level, msg: logs.append((level, msg)) # type: ignore[method-assign] + + def fake_execute(task_id: int, config: dict, total: int) -> None: + now = time.monotonic() + if int(task_id) == id1: + runner._task_started_at[int(task_id)] = now + raise RuntimeError("boom-first") + # Simulate task 2 having waited 6.5s in the lane queue before starting. + runner._task_started_at[int(task_id)] = now + 6.5 + + def fake_submit(lane: TaskLane, fn, *args, **_kwargs): + fut: Future[None] = Future() + + def _run(): + try: + fn(args[0], args[1], args[2]) + fut.set_result(None) + except Exception as exc: # noqa: BLE001 + fut.set_exception(exc) + + threading.Thread(target=_run, daemon=True).start() + return fut + + with ( + patch.object(runner, "_execute_one", side_effect=fake_execute), + patch("web.backend.services.douyu_runner.submit", side_effect=fake_submit), + ): + runner.run() + + error_logs = [msg for lvl, msg in logs if lvl == "error"] + assert any(f"task_id={id1}" in msg for msg in error_logs), error_logs + assert all(f"task_id={id2}" not in msg for msg in error_logs) + info_logs = [msg for lvl, msg in logs if lvl == "info"] + assert any(f"task_id={id2}" in msg and "排队" in msg for msg in info_logs), info_logs + assert all(f"task_id={id1}" not in msg or "排队" not in msg for msg in info_logs) + + +class TestSlowQueryIndexesAndRoleNorm(_TestBase): + def test_role_norm_virtual_column_and_new_indexes_exist(self): + row = PlatformFulfillmentTask( + source_system="order_site", + source_order_id="p0p1-ord", + source_order_item_id="p0p1-item", + source_fulfillment_id="p0p1-ff", + platform_order_id="ORD-P0P1", + provider="91kaquan", + shop_id="s1", + shop_name="shop", + sku_code="sku", + sku_name="sku", + internal_sku_key="sku", + quantity=1, + order_amount_fen=100, + target_platform="douyu", + scope="elite", + customer_role_name=" MiXeD_Role_名称 ", + flow_version=2, + ) + self.session.add(row) + self.session.commit() + + found = ( + self.session.query(PlatformFulfillmentTask) + .filter(PlatformFulfillmentTask.customer_role_norm == "mixed_role_名称") + .one() + ) + assert found.id == row.id + + inspector = inspect(self.engine) + event_indexes = {idx["name"] for idx in inspector.get_indexes("account_events")} + assert "ix_account_events_event_subject_occurred" in event_indexes + assert "ix_account_events_type_occurred" in event_indexes + + sync_indexes = {idx["name"] for idx in inspector.get_indexes("account_sync_runs")} + assert "ix_account_sync_runs_trend_cover" in sync_indexes + + commodity_indexes = { + idx["name"] for idx in inspector.get_indexes("account_commodity_states") + } + assert "ix_account_commodity_skin_options" in commodity_indexes + + pf_indexes = { + idx["name"] for idx in inspector.get_indexes("platform_fulfillment_tasks") + } + assert "ix_platform_fulfillment_role_norm" in pf_indexes + + +class TestProxyNonBlockingAndHttpSessionClosing: + def test_verify_proxies_concurrent_returns_fast_without_waiting_slow_probe(self): + def fake_verify(proxy_url: str, timeout=(3, 5)): + if "slow" in proxy_url: + time.sleep(2.0) + return False, "timeout" + return True, "ok" + + started = time.monotonic() + with patch( + "core.douyu.proxy_verifier.verify_proxy_url", side_effect=fake_verify + ): + proxy, msg = verify_proxies_concurrent( + ["http://slow:1", "http://fast:2"], + return_all=False, + ) + elapsed = time.monotonic() - started + + assert proxy == "http://fast:2" + assert msg == "ok" + assert elapsed < 0.8 + + def test_clients_close_owned_http_sessions(self): + activity = DouyuActivityClient("acf_uid=1") + activity.session.close = MagicMock() # type: ignore[method-assign] + with activity: + pass + activity.session.close.assert_called_once() + + owned_recharge = FishFinRechargeClient( + FishFinRechargeConfig( + base_url="https://supplier.example", + app_id="app", + app_secret="sec", + ) + ) + owned_recharge.session.close = MagicMock() # type: ignore[method-assign] + with owned_recharge: + pass + owned_recharge.session.close.assert_called_once() + + external_sess = MagicMock() + borrowed_recharge = FishFinRechargeClient( + FishFinRechargeConfig( + base_url="https://supplier.example", + app_id="app", + app_secret="sec", + ), + session=external_sess, + ) + borrowed_recharge.close() + external_sess.close.assert_not_called() + + verifier = EmailVerifier(username="u@e.com", password="p") + mock_rc_sess = MagicMock() + verifier._rc_session = mock_rc_sess + verifier._rc_logged_in = True + verifier.disconnect() + mock_rc_sess.close.assert_called_once() + + # Failed login attempt must still close its temporary requests.Session. + temp_sess = MagicMock() + temp_sess.get.return_value = SimpleNamespace(text="no-token-here") + with ( + patch("core.douyu.email_verifier.requests.Session", return_value=temp_sess), + ): + ok, pwd_err = verifier._try_roundcube_login("wrong") + assert (ok, pwd_err) == (False, False) + temp_sess.close.assert_called_once() + + loginer = DouyuLogin( + SimpleNamespace( + username="u", + password="p", + email="e@example.com", + email_password="ep", + email_imap_server="", + email_imap_port=993, + email_imap_ssl=True, + ) + ) + loginer.session.close = MagicMock() # type: ignore[method-assign] + with loginer: + pass + loginer.session.close.assert_called_once() + + assert pytest is not None diff --git a/tests/test_douyu_p2_observability.py b/tests/test_douyu_p2_observability.py new file mode 100644 index 0000000..fc25886 --- /dev/null +++ b/tests/test_douyu_p2_observability.py @@ -0,0 +1,303 @@ +"""P2 运维与队列可观测性优化回归测试。""" + +from __future__ import annotations + +import threading +import time +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +from web.backend import background_runtime +from web.backend.models import ( + Account, + AutomationJob, + DouyuTask, + User, +) +from web.backend.routers import automation as automation_router +from web.backend.routers import douyu as douyu_router +from web.backend.services import ( + binding_poll_scheduler, + execution_worker, + payment_poll_scheduler, + task_runtime, +) +from web.backend.services.account_observability import account_platform_status +from web.backend.services.account_work_queue import ( + STALE_RUNNING_SECONDS, + enqueue_account_work, + recover_stale_running_account_work, +) +from web.backend.services.automation.jobs import account_sync_queue +from web.backend.services.douyu_runner_core import DouyuBatchRegistry +from web.backend.services.execution_jobs import ( + JOB_DOUYU_BATCH, + LANE_FULFILLMENT, + ExecutionEventBatchWriter, + enqueue_execution_job, +) + + +def _seed_user_and_account(db, suffix: str) -> tuple[User, Account]: + user = User(username=f"p2-user-{suffix}", password_hash="h", role="super_admin") + account = Account( + username=f"p2-acc-{suffix}", + password="p", + email=f"p2-{suffix}@example.com", + email_password="ep", + uid=f"99{suffix}"[:32], + cookie="acf_uid=99; acf_ltkid=1; acf_username=p2", + ) + db.add_all([user, account]) + db.commit() + return user, account + + +def test_cleanup_orphan_tasks_preserves_durable_execution_job_batches(db): + user, account = _seed_user_and_account(db, "orphan") + enqueue_execution_job( + db, + job_type=JOB_DOUYU_BATCH, + lane_scope=LANE_FULFILLMENT, + batch_id="durable-active-batch", + payload={"task_type": "query_points", "payload": {}}, + created_by=int(user.id), + ) + durable_task = DouyuTask( + batch_id="durable-active-batch", + account_id=int(account.id), + task_type="query_points", + status="running", + message="执行中", + created_by=int(user.id), + ) + orphan_task = DouyuTask( + batch_id="lost-orphan-batch", + account_id=int(account.id), + task_type="query_points", + status="running", + message="执行中", + created_by=int(user.id), + ) + db.add_all([durable_task, orphan_task]) + db.commit() + + result = douyu_router.cleanup_orphan_tasks(db=db, current=user) + + db.refresh(durable_task) + db.refresh(orphan_task) + assert result["cleaned"] == 1 + assert durable_task.status == "running" + assert orphan_task.status == "stopped" + + +def test_douyu_batch_registry_evicts_expired_finished_batches(monkeypatch): + monkeypatch.setenv("DOUYU_BATCH_REGISTRY_FINISHED_TTL_SECONDS", "10") + registry = DouyuBatchRegistry() + dummy_runner = SimpleNamespace(stop=lambda: None) + + registry.register("active-batch", None, None, dummy_runner) + registry.register("expired-batch", None, None, dummy_runner) + registry.register("recent-finished-batch", None, None, dummy_runner) + + registry.mark_finished("expired-batch") + registry.mark_finished("recent-finished-batch") + registry.get("expired-batch")["updated_at"] = time.time() - 30 + + stats = registry.stats() + + assert registry.get("expired-batch") is None + assert registry.get("recent-finished-batch") is not None + assert registry.active_ids() == {"active-batch"} + assert stats == {"active": 1, "finished": 1, "total": 2} + + +def test_task_runtime_lane_stats_tracks_active_queued_and_rejected(monkeypatch): + monkeypatch.setenv("TASK_LANE_COLLAB_RECOMMEND_WORKERS", "1") + monkeypatch.setenv("TASK_LANE_COLLAB_RECOMMEND_MAX_IN_FLIGHT", "2") + with task_runtime._LOCK: + old_runtime = task_runtime._RUNTIMES.pop(task_runtime.TaskLane.COLLAB_RECOMMEND, None) + if old_runtime is not None: + old_runtime.executor.shutdown(wait=False) + + entered = threading.Event() + release = threading.Event() + try: + def block(): + entered.set() + release.wait(timeout=5) + return "ok" + + f1 = task_runtime.try_submit(task_runtime.TaskLane.COLLAB_RECOMMEND, block) + assert f1 is not None + assert entered.wait(timeout=2) + + f2 = task_runtime.try_submit(task_runtime.TaskLane.COLLAB_RECOMMEND, lambda: "second") + assert f2 is not None + f3 = task_runtime.try_submit(task_runtime.TaskLane.COLLAB_RECOMMEND, lambda: "rejected") + assert f3 is None + + stats = task_runtime.lane_stats()[task_runtime.TaskLane.COLLAB_RECOMMEND.value] + assert stats["workers"] == 1 + assert stats["max_in_flight"] == 2 + assert stats["admission_value"] == 0 + assert stats["in_flight"] == 2 + assert stats["active"] == 1 + assert stats["queued"] == 1 + assert stats["rejected"] >= 1 + assert stats["submitted"] >= 2 + + release.set() + assert f1.result(timeout=5) == "ok" + assert f2.result(timeout=5) == "second" + + after = task_runtime.lane_stats()[task_runtime.TaskLane.COLLAB_RECOMMEND.value] + assert after["in_flight"] == 0 + assert after["active"] == 0 + assert after["admission_value"] == 2 + finally: + release.set() + with task_runtime._LOCK: + rt = task_runtime._RUNTIMES.pop(task_runtime.TaskLane.COLLAB_RECOMMEND, None) + if rt is not None: + rt.executor.shutdown(wait=True) + + +def test_poll_scheduler_and_execution_worker_status_expose_health(monkeypatch): + monkeypatch.setattr(binding_poll_scheduler, "available_slots", lambda _lane: 4) + monkeypatch.setattr(binding_poll_scheduler, "_claim_due_binding_tasks", lambda _limit: []) + assert binding_poll_scheduler.run_binding_poll_dispatch_once(10) == 0 + b_status = binding_poll_scheduler.scheduler_status() + assert "last_claimed" in b_status + assert "consecutive_errors" in b_status + + monkeypatch.setattr(payment_poll_scheduler, "available_slots", lambda _lane: 4) + monkeypatch.setattr(payment_poll_scheduler, "_claim_due_payment_tasks", lambda _limit: []) + assert payment_poll_scheduler.run_payment_poll_dispatch_once(10) == 0 + p_status = payment_poll_scheduler.scheduler_status() + assert "last_claimed" in p_status + assert "consecutive_errors" in p_status + + writer = ExecutionEventBatchWriter() + assert writer.status() == { + "running": False, + "pending": 0, + "flushing": False, + "failed_batches": 0, + } + w_status = execution_worker.execution_job_worker_status() + assert "inflight" in w_status + assert "inflight_total" in w_status + assert "event_writer" in w_status + + +def test_automation_list_jobs_prefers_background_heartbeat_runtime_and_queues( + db, + monkeypatch, + tmp_path, +): + user, account = _seed_user_and_account(db, "auto") + enqueue_execution_job( + db, + job_type=JOB_DOUYU_BATCH, + lane_scope=LANE_FULFILLMENT, + batch_id="bg-queued-batch", + payload={}, + created_by=int(user.id), + ) + db.add( + DouyuTask( + batch_id="bg-queued-batch", + account_id=int(account.id), + task_type="get_bind_qr", + queue_lane="binding_poll", + status="running", + next_run_at=datetime.now(UTC) - timedelta(seconds=5), + created_by=int(user.id), + ) + ) + db.commit() + + heartbeat_path = tmp_path / "background_runtime.json" + monkeypatch.setenv("BACKGROUND_RUNTIME_HEARTBEAT_PATH", str(heartbeat_path)) + monkeypatch.setattr( + "web.backend.services.automation.scheduler.scheduler_status", + lambda: { + "enabled": True, + "running": True, + "tick_seconds": 30, + "job_interval_seconds": 300, + "registered": ["account_sync_queue"], + "in_flight": ["account_sync_queue"], + }, + ) + background_runtime._write_runtime_heartbeat() + + monkeypatch.setattr( + automation_router, + "scheduler_status", + lambda: { + "enabled": True, + "running": False, + "tick_seconds": 30, + "job_interval_seconds": 300, + "registered": [], + "in_flight": [], + }, + ) + + payload = automation_router.list_jobs(db=db, current=user) + + assert payload["scheduler"]["process"] == "background" + assert payload["scheduler"]["in_flight"] == ["account_sync_queue"] + assert "douyu_batches" in payload["runtime"] + assert payload["runtime"]["queues"]["execution_jobs"]["fulfillment"]["queued"] == 1 + assert payload["runtime"]["queues"]["binding_poll"] == {"running": 1, "due": 1} + assert payload["runtime"]["queues"]["payment_poll"] == {"running": 0, "due": 0} + + +def test_recover_stale_running_account_work_and_observability_alert(db, monkeypatch): + _, account = _seed_user_and_account(db, "stalework") + now = datetime.now(UTC).replace(microsecond=0) + stale = enqueue_account_work( + db, + account_id=int(account.id), + work_type="storehome_sync", + due_at=now - timedelta(hours=2), + max_attempts=2, + ) + stale.status = "running" + stale.started_at = now - timedelta(seconds=STALE_RUNNING_SECONDS + 120) + stale.attempt_count = 1 + db.commit() + + status = account_platform_status( + db, + now=now, + include_trends=False, + include_supply=False, + include_diagnostics=False, + ) + assert any(a["code"] == "account_work_stale_running" for a in status["alerts"]) + + monkeypatch.setattr( + account_sync_queue, + "run_account_sync_queue", + lambda _db, batch_size=20: {"scanned": 0, "success": 0, "failed": 0, "message": "ok"}, + ) + job = AutomationJob(key="account_sync_queue", title="sync", batch_size=20) + outcome = account_sync_queue.run_account_sync_queue_job(db, job) + + db.refresh(stale) + assert outcome["recovered_stale"] == 1 + assert stale.status == "pending" + assert "疑似卡死" in stale.last_error + + # Verify exhausted attempts transition cleanly to failed when recovered again. + stale.status = "running" + stale.started_at = now - timedelta(seconds=STALE_RUNNING_SECONDS + 60) + stale.attempt_count = 2 + db.commit() + assert recover_stale_running_account_work(db, now=now) == 1 + db.refresh(stale) + assert stale.status == "failed" diff --git a/tests/test_douyu_tasks_retention.py b/tests/test_douyu_tasks_retention.py index 3979ee1..54b204d 100644 --- a/tests/test_douyu_tasks_retention.py +++ b/tests/test_douyu_tasks_retention.py @@ -15,6 +15,7 @@ from sqlalchemy import func from tests.support.db import get_test_engine, make_test_session from web.backend.models import ( Account, + AccountSyncRun, AutomationJob, DouyuTask, ExecutionJob, @@ -30,6 +31,7 @@ class _Base: def setup_method(self): self.engine = get_test_engine() self.session = make_test_session(self.engine) + self.session.query(AccountSyncRun).delete() self.session.query(DouyuTask).delete() self.session.query(AutomationJob).filter( AutomationJob.key == retention.JOB_KEY @@ -258,6 +260,37 @@ class TestRetention(_Base): assert out["deleted_execution_jobs"] == 1 assert self.session.query(ExecutionJob).count() == 0 + def test_old_account_sync_runs_cleaned_by_retention(self): + self.session.add_all( + [ + AccountSyncRun( + account_id=self.account_id, + domain="points", + started_at=NOW - timedelta(days=20), + finished_at=NOW - timedelta(days=20), + status="success", + duration_ms=120, + ), + AccountSyncRun( + account_id=self.account_id, + domain="points", + started_at=NOW - timedelta(days=3), + finished_at=NOW - timedelta(days=3), + status="success", + duration_ms=80, + ), + ] + ) + self.session.commit() + + out = self.run(noise_days=7, business_days=90, sync_run_days=14) + + assert out["deleted_sync_runs"] == 1 + assert out["sync_run_days"] == 14 + remaining_runs = self.session.query(AccountSyncRun).all() + assert len(remaining_runs) == 1 + assert remaining_runs[0].duration_ms == 80 + class TestClassification(_Base): def test_noise_list_has_no_duplicates(self): diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 1b55cdb..8d204af 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261129_0140" +HEAD_REVISION = "20261129_0141" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( @@ -91,6 +91,7 @@ _LATER_ORM_COLUMNS = { "exchange_result_image_key": "VARCHAR(512) NOT NULL DEFAULT ''", "exchange_result_image_saved_at": "DATETIME NULL", "customer_role_name": "VARCHAR(128) NOT NULL DEFAULT ''", + "customer_role_norm": "VARCHAR(128) GENERATED ALWAYS AS (lower(trim(customer_role_name))) VIRTUAL NULL", "customer_platform": "VARCHAR(16) NOT NULL DEFAULT ''", "customer_system": "VARCHAR(16) NOT NULL DEFAULT ''", "customer_home_images": "JSON NULL", @@ -248,6 +249,7 @@ class TestMigrationSmoke: # 迁移新增的复合查询索引(不入模型,但应存在)。 for index_name in EXTRA_INDEXES: assert index_name in all_db_indexes, f"迁移链未创建索引 {index_name}" + assert "ix_account_sync_runs_started_domain_status" not in all_db_indexes finally: database_module.DATABASE_URL = original_url with admin_engine.begin() as conn: diff --git a/uv.lock b/uv.lock index daeba82..5705a2c 100644 --- a/uv.lock +++ b/uv.lock @@ -381,7 +381,7 @@ wheels = [ [[package]] name = "live-hub-py" -version = "0.4.22" +version = "0.4.23" source = { editable = "." } dependencies = [ { name = "alembic" }, diff --git a/web/backend/background_runtime.py b/web/backend/background_runtime.py index 9949c1f..0bbc6da 100644 --- a/web/backend/background_runtime.py +++ b/web/backend/background_runtime.py @@ -38,12 +38,34 @@ def _runtime_heartbeat_path() -> Path: def _runtime_heartbeat_payload() -> dict[str, Any]: + from .database import worker_engine from .services.automation.scheduler import scheduler_status + from .services.binding_poll_scheduler import ( + scheduler_status as binding_poll_status, + ) + from .services.douyu_runner_core import douyu_batch_registry + from .services.execution_worker import execution_job_worker_status + from .services.payment_poll_scheduler import ( + scheduler_status as payment_poll_status, + ) + from .services.task_runtime import lane_stats return { "pid": os.getpid(), "updatedAt": datetime.now(UTC).isoformat(), "scheduler": scheduler_status(), + "runtime": { + "task_lanes": lane_stats(), + "worker_db_pool": ( + getattr(worker_engine.pool, "status", lambda: "")() + if callable(getattr(worker_engine.pool, "status", None)) + else "" + ), + "binding_poll": binding_poll_status(), + "payment_poll": payment_poll_status(), + "execution_jobs": execution_job_worker_status(), + "douyu_batches": douyu_batch_registry.stats(), + }, } @@ -115,8 +137,10 @@ def background_runtime_status() -> dict[str, Any]: "staleAfterSeconds": _HEARTBEAT_STALE_SECONDS, "pid": None, "scheduler": {}, + "runtime": {}, } scheduler = payload.get("scheduler") + runtime = payload.get("runtime") return { "running": age_seconds <= _HEARTBEAT_STALE_SECONDS, "heartbeatAt": heartbeat_at.isoformat(), @@ -124,6 +148,7 @@ def background_runtime_status() -> dict[str, Any]: "staleAfterSeconds": _HEARTBEAT_STALE_SECONDS, "pid": payload.get("pid"), "scheduler": scheduler if isinstance(scheduler, dict) else {}, + "runtime": runtime if isinstance(runtime, dict) else {}, } diff --git a/web/backend/database.py b/web/backend/database.py index 3a55009..56a12e6 100644 --- a/web/backend/database.py +++ b/web/backend/database.py @@ -246,12 +246,30 @@ class UTCDateTime(TypeDecorator): def get_db(): """FastAPI 依赖:提供数据库会话,请求结束自动关闭。""" db = SessionLocal() + db.info["managed_request_session"] = True try: yield db finally: db.close() +def release_idle_session(db) -> bool: + """在执行阻塞 HTTP / sleep 前释放干净托管会话的事务与连接池连接。 + + 仅对通过 ``get_db()`` 或 worker 托管标记创建的会话生效,且会话内不能有 + 未提交的新增/修改/删除对象,避免误伤单元测试中的未提交夹具或脏写状态。 + """ + info = getattr(db, "info", None) + if not isinstance(info, dict) or not ( + info.get("managed_request_session") or info.get("managed_worker_session") + ): + return False + if getattr(db, "new", None) or getattr(db, "dirty", None) or getattr(db, "deleted", None): + return False + db.rollback() + return True + + def init_db(): """执行数据库迁移 + 写入初始数据。""" run_migrations() diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index 39bc53e..18ea63d 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -561,6 +561,10 @@ "20261129_0140_add_account_elite_capability_projection.py": { "revision": "20261129_0140", "sha256": "c19909f65b4826cd292176b71481f45eb4c1fb211b1db7923df7e92e54903c6d" + }, + "20261129_0141_douyu_slow_query_indexes.py": { + "revision": "20261129_0141", + "sha256": "537ffb0a472c80d3a499c3c268aa62a2f5235ccc5399a81955a0e14d8721ea1f" } } } diff --git a/web/backend/migrations/versions/20261129_0141_douyu_slow_query_indexes.py b/web/backend/migrations/versions/20261129_0141_douyu_slow_query_indexes.py new file mode 100644 index 0000000..45fb089 --- /dev/null +++ b/web/backend/migrations/versions/20261129_0141_douyu_slow_query_indexes.py @@ -0,0 +1,175 @@ +"""add douyu slow query covering indexes and role_norm column + +Revision ID: 20261129_0141 +Revises: 20261129_0140 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261129_0141" +down_revision: str | None = "20261129_0140" +branch_labels: str | None = None +depends_on: str | None = None + + +def _has_column(inspector: sa.Inspector, table: str, column: str) -> bool: + return any(col["name"] == column for col in inspector.get_columns(table)) + + +def _has_index(inspector: sa.Inspector, table: str, index_name: str) -> bool: + return any(idx["name"] == index_name for idx in inspector.get_indexes(table)) + + +def upgrade() -> None: + bind = op.get_bind() + inspector = sa.inspect(bind) + + if inspector.has_table("account_events"): + if not _has_index( + inspector, "account_events", "ix_account_events_event_subject_occurred" + ): + op.create_index( + "ix_account_events_event_subject_occurred", + "account_events", + ["event_type", "subject_type", "subject_key", "occurred_at"], + ) + if not _has_index( + inspector, "account_events", "ix_account_events_type_occurred" + ): + op.create_index( + "ix_account_events_type_occurred", + "account_events", + ["event_type", "occurred_at"], + ) + + if inspector.has_table("account_sync_runs"): + if not _has_index( + inspector, "account_sync_runs", "ix_account_sync_runs_trend_cover" + ): + op.create_index( + "ix_account_sync_runs_trend_cover", + "account_sync_runs", + ["started_at", "domain", "status", "duration_ms"], + ) + if _has_index( + inspector, + "account_sync_runs", + "ix_account_sync_runs_started_domain_status", + ): + op.drop_index( + "ix_account_sync_runs_started_domain_status", + table_name="account_sync_runs", + ) + + if inspector.has_table("account_commodity_states") and not _has_index( + inspector, + "account_commodity_states", + "ix_account_commodity_skin_options", + ): + op.create_index( + "ix_account_commodity_skin_options", + "account_commodity_states", + [ + "platform", + "account_eligibility", + "offer_state", + "valid_until", + "scope", + "commodity_id", + "commodity_name", + ], + ) + + if inspector.has_table("platform_fulfillment_tasks"): + if not _has_column( + inspector, "platform_fulfillment_tasks", "customer_role_norm" + ): + op.add_column( + "platform_fulfillment_tasks", + sa.Column( + "customer_role_norm", + sa.String(length=128), + sa.Computed( + "lower(trim(customer_role_name))", + persisted=False, + ), + nullable=True, + ), + ) + inspector = sa.inspect(bind) + if not _has_index( + inspector, + "platform_fulfillment_tasks", + "ix_platform_fulfillment_role_norm", + ): + op.create_index( + "ix_platform_fulfillment_role_norm", + "platform_fulfillment_tasks", + ["flow_version", "customer_role_norm", "execution_status"], + ) + + +def downgrade() -> None: + bind = op.get_bind() + inspector = sa.inspect(bind) + + if inspector.has_table("platform_fulfillment_tasks"): + if _has_index( + inspector, + "platform_fulfillment_tasks", + "ix_platform_fulfillment_role_norm", + ): + op.drop_index( + "ix_platform_fulfillment_role_norm", + table_name="platform_fulfillment_tasks", + ) + if _has_column(inspector, "platform_fulfillment_tasks", "customer_role_norm"): + op.drop_column("platform_fulfillment_tasks", "customer_role_norm") + + if inspector.has_table("account_commodity_states") and _has_index( + inspector, + "account_commodity_states", + "ix_account_commodity_skin_options", + ): + op.drop_index( + "ix_account_commodity_skin_options", + table_name="account_commodity_states", + ) + + if inspector.has_table("account_sync_runs"): + if not _has_index( + inspector, + "account_sync_runs", + "ix_account_sync_runs_started_domain_status", + ): + op.create_index( + "ix_account_sync_runs_started_domain_status", + "account_sync_runs", + ["started_at", "domain", "status"], + ) + if _has_index( + inspector, "account_sync_runs", "ix_account_sync_runs_trend_cover" + ): + op.drop_index( + "ix_account_sync_runs_trend_cover", + table_name="account_sync_runs", + ) + + if inspector.has_table("account_events"): + if _has_index( + inspector, "account_events", "ix_account_events_type_occurred" + ): + op.drop_index( + "ix_account_events_type_occurred", + table_name="account_events", + ) + if _has_index( + inspector, "account_events", "ix_account_events_event_subject_occurred" + ): + op.drop_index( + "ix_account_events_event_subject_occurred", + table_name="account_events", + ) diff --git a/web/backend/models.py b/web/backend/models.py index 9686899..f893c1f 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -2039,6 +2039,18 @@ class AccountEvent(Base): # 「某个客服这段时间做了什么」——池化后客服不再持有账号, # 这条是管理侧追责与对账的主查询路径,此前没有任何索引可用。 Index("ix_account_events_actor_occurred", "actor_id", "occurred_at"), + Index( + "ix_account_events_event_subject_occurred", + "event_type", + "subject_type", + "subject_key", + "occurred_at", + ), + Index( + "ix_account_events_type_occurred", + "event_type", + "occurred_at", + ), ) @@ -2197,6 +2209,16 @@ class AccountCommodityState(Base): "account_eligibility", "valid_until", ), + Index( + "ix_account_commodity_skin_options", + "platform", + "account_eligibility", + "offer_state", + "valid_until", + "scope", + "commodity_id", + "commodity_name", + ), ) @@ -2493,6 +2515,11 @@ class PlatformFulfillmentTask(Base): customer_role_name: Mapped[str] = mapped_column( String(128), nullable=False, default="", server_default="" ) + customer_role_norm: Mapped[str | None] = mapped_column( + String(128), + Computed("lower(trim(customer_role_name))", persisted=False), + nullable=True, + ) customer_platform: Mapped[str] = mapped_column( String(16), nullable=False, default="", server_default="" ) @@ -2581,6 +2608,12 @@ class PlatformFulfillmentTask(Base): "next_allocate_at", "id", ), + Index( + "ix_platform_fulfillment_role_norm", + "flow_version", + "customer_role_norm", + "execution_status", + ), ) @@ -2739,10 +2772,11 @@ class AccountSyncRun(Base): "started_at", ), Index( - "ix_account_sync_runs_started_domain_status", + "ix_account_sync_runs_trend_cover", "started_at", "domain", "status", + "duration_ms", ), ) diff --git a/web/backend/routers/automation.py b/web/backend/routers/automation.py index 9604cda..b6529e2 100644 --- a/web/backend/routers/automation.py +++ b/web/backend/routers/automation.py @@ -12,7 +12,7 @@ from typing import Any from fastapi import APIRouter, Depends, HTTPException, Query from pydantic import BaseModel, Field -from sqlalchemy import select +from sqlalchemy import case, func, select from sqlalchemy.orm import Session from ..database import get_db @@ -21,6 +21,8 @@ from ..models import ( Account, AutomationJob, AutomationRun, + DouyuTask, + ExecutionJob, LoginQuotaSetting, LoginTask, User, @@ -180,6 +182,8 @@ def list_jobs( from ..services.binding_poll_scheduler import ( scheduler_status as binding_poll_status, ) + from ..services.douyu_runner_core import douyu_batch_registry + from ..services.execution_jobs import STATUS_QUEUED, STATUS_RUNNING from ..services.execution_worker import execution_job_worker_status from ..services.payment_poll_scheduler import ( scheduler_status as payment_poll_status, @@ -203,6 +207,8 @@ def list_jobs( "pid": background_runtime.get("pid"), "heartbeatAt": background_runtime.get("heartbeatAt"), } + if "in_flight" in background_scheduler: + scheduler_state["in_flight"] = background_scheduler["in_flight"] else: scheduler_state = { **scheduler_state, @@ -210,16 +216,91 @@ def list_jobs( "heartbeatAt": background_runtime.get("heartbeatAt"), } + bg_rt_raw = background_runtime.get("runtime") + bg_rt = ( + bg_rt_raw + if scheduler_state["process"] == "background" and isinstance(bg_rt_raw, dict) + else {} + ) + local_worker_pool = ( + getattr(worker_engine.pool, "status", lambda: "")() + if callable(getattr(worker_engine.pool, "status", None)) + else "" + ) + + now = datetime.now(UTC) + exec_rows = ( + db.query( + ExecutionJob.lane_scope, + ExecutionJob.status, + func.count(ExecutionJob.id), + ) + .filter(ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING))) + .group_by(ExecutionJob.lane_scope, ExecutionJob.status) + .all() + ) + exec_backlog: dict[str, dict[str, int]] = {} + for lane_scope, status, count in exec_rows: + bucket = exec_backlog.setdefault(str(lane_scope), {"queued": 0, "running": 0}) + if status in bucket: + bucket[str(status)] = int(count or 0) + + poll_rows = ( + db.query( + DouyuTask.queue_lane, + func.count(DouyuTask.id), + func.sum( + case( + ( + DouyuTask.next_run_at <= now, + 1, + ), + else_=0, + ) + ), + ) + .filter( + DouyuTask.queue_lane.in_(("binding_poll", "payment_poll")), + DouyuTask.status == "running", + ) + .group_by(DouyuTask.queue_lane) + .all() + ) + poll_backlog: dict[str, dict[str, int]] = { + "binding_poll": {"running": 0, "due": 0}, + "payment_poll": {"running": 0, "due": 0}, + } + for queue_lane, total, due in poll_rows: + poll_backlog[str(queue_lane)] = { + "running": int(total or 0), + "due": int(due or 0), + } + return { "scheduler": scheduler_state, "runtime": { - "task_lanes": lane_stats(), - "worker_db_pool": getattr(worker_engine.pool, "status", lambda: "")() - if callable(getattr(worker_engine.pool, "status", None)) - else "", - "binding_poll": binding_poll_status(), - "payment_poll": payment_poll_status(), - "execution_jobs": execution_job_worker_status(), + "task_lanes": bg_rt.get("task_lanes") + if isinstance(bg_rt.get("task_lanes"), dict) + else lane_stats(), + "worker_db_pool": bg_rt["worker_db_pool"] + if isinstance(bg_rt.get("worker_db_pool"), str) + else local_worker_pool, + "binding_poll": bg_rt.get("binding_poll") + if isinstance(bg_rt.get("binding_poll"), dict) + else binding_poll_status(), + "payment_poll": bg_rt.get("payment_poll") + if isinstance(bg_rt.get("payment_poll"), dict) + else payment_poll_status(), + "execution_jobs": bg_rt.get("execution_jobs") + if isinstance(bg_rt.get("execution_jobs"), dict) + else execution_job_worker_status(), + "douyu_batches": bg_rt.get("douyu_batches") + if isinstance(bg_rt.get("douyu_batches"), dict) + else douyu_batch_registry.stats(), + "queues": { + "execution_jobs": exec_backlog, + **poll_backlog, + }, "background_runtime": background_runtime, }, "pending_relogin": pending_relogin, diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index 13e5c53..524e7c4 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -193,7 +193,13 @@ async def supplier_recharge_callback(request: Request, db: Session = Depends(get except FishFinRechargeConfigError as exc: logger.error("[douyu] 供应商直充回调配置无效: {}", exc) raise HTTPException(status_code=503, detail="供应商直充回调未配置") from exc - if not client.verify_response_sign(payload, "POST"): + try: + verified = client.verify_response_sign(payload, "POST") + finally: + close = getattr(client, "close", None) + if callable(close): + close() + if not verified: logger.warning("[douyu] 供应商直充回调验签失败: keys={}", sorted(payload)) raise HTTPException(status_code=401, detail="供应商回调签名无效") @@ -1285,14 +1291,19 @@ def list_live_goods( """实时读取精英宝典活动商品,不依赖账号或本地刷新任务。""" del current config = ensure_douyu_config(db) + client = activity_client() try: goods = query_activity_goods( - activity_client(), + client, manual_id=str(douyu_config_value("manual_id", config.manual_id)), rid=str(douyu_config_value("rid", config.rid)), ) except DouyuActivityError as exc: raise HTTPException(status_code=502, detail=f"活动商品加载失败:{exc}") from exc + finally: + close = getattr(client, "close", None) + if callable(close): + close() now = datetime.now(UTC) return [ DouyuGoodsOut( @@ -1858,10 +1869,18 @@ def cleanup_orphan_tasks( db: Session = Depends(get_db), current: User = Depends(require_permission("douyu:task")), ): - """手动清理没有内存执行器接管的斗鱼任务。""" + """手动清理没有内存执行器或持久队列接管的斗鱼任务。""" + durable_batch_ids = { + str(batch_id) + for (batch_id,) in ( + db.query(ExecutionJob.batch_id) + .filter(ExecutionJob.status.in_((STATUS_QUEUED, STATUS_RUNNING))) + .all() + ) + } cleaned = cleanup_orphan_douyu_tasks( db, - active_batch_ids=douyu_batch_registry.active_ids(), + active_batch_ids=douyu_batch_registry.active_ids() | durable_batch_ids, statuses=DOUYU_ACTIVE_TASK_STATUSES, message="任务已中断(无执行器接管)", ) diff --git a/web/backend/routers/douyu_collab.py b/web/backend/routers/douyu_collab.py index 1bc0838..8b147f5 100644 --- a/web/backend/routers/douyu_collab.py +++ b/web/backend/routers/douyu_collab.py @@ -20,7 +20,7 @@ from fastapi import ( ) from sqlalchemy.orm import Session -from ..database import get_db +from ..database import get_db, release_idle_session from ..deps import authenticate_websocket, get_current_user, require_permission from ..errors import ApiError from ..models import User @@ -425,6 +425,7 @@ def verify_external_orders_batch( interval = _verify_batch_interval() for index, order_id in enumerate(ids): if index and interval: + release_idle_session(db) time.sleep(interval) try: order = collab.get_order(db, order_id) diff --git a/web/backend/services/account_check_service.py b/web/backend/services/account_check_service.py index 1d1d2a2..38c27d0 100644 --- a/web/backend/services/account_check_service.py +++ b/web/backend/services/account_check_service.py @@ -308,7 +308,7 @@ class AccountCheckRunner: finished_at=None, ) try: - result = DouyuLogin( + loginer = DouyuLogin( cast( AccountLike, SimpleNamespace( @@ -327,7 +327,13 @@ class AccountCheckRunner: proxy_fetcher=self._shared_proxy_fetcher, stop_event=self._stop, api_strategy=create_login_api_strategy(self.batch.api_strategy), - ).check_account() + ) + try: + result = loginer.check_account() + finally: + close = getattr(loginer, "close", None) + if callable(close): + close() except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 self._set_item( index, status="error", message=f"检测异常: {exc}", finished_at=_now() diff --git a/web/backend/services/account_exchange_sync_service.py b/web/backend/services/account_exchange_sync_service.py index 69956e7..04077b8 100644 --- a/web/backend/services/account_exchange_sync_service.py +++ b/web/backend/services/account_exchange_sync_service.py @@ -9,10 +9,12 @@ from sqlalchemy.orm import Session from core.douyu import DouyuActivityClient +from ..database import release_idle_session from ..models import Account from .account_sync_service import ( DOMAIN_EXCHANGE_RECORDS, get_sync_state, + lock_account_row, record_sync_success, ) from .business_events import record_official_exchange @@ -74,6 +76,8 @@ def persist_official_exchange_records( pairs: list[tuple[str, dict[str, Any]]], ) -> int: """把官方记录幂等补成账号事件,返回新写入数量。""" + if account.id is not None and pairs: + lock_account_row(db, int(account.id)) added = 0 for scope, record in pairs: if not isinstance(record, dict): @@ -195,7 +199,9 @@ def sync_exchange_records( max_pages: int = 1, ) -> dict[str, Any]: """同步官方记录、补事件并保存可回放的按作用域原始投影。""" + account_id = int(account.id) if account.id is not None else None observed_at = datetime.now(UTC) + released = release_idle_session(db) pairs, errors = fetch_exchange_records( client, config, @@ -203,6 +209,10 @@ def sync_exchange_records( scopes=scopes, max_pages=max_pages, ) + if released and account_id is not None: + account = db.get(Account, account_id) or account + if account.id is not None: + lock_account_row(db, int(account.id)) changed = persist_official_exchange_records(db, account, pairs) previous = get_sync_state( db, diff --git a/web/backend/services/account_observability.py b/web/backend/services/account_observability.py index 5666466..64e0019 100644 --- a/web/backend/services/account_observability.py +++ b/web/backend/services/account_observability.py @@ -26,6 +26,7 @@ from .account_supply_service import ( load_supply_snapshot_inventories, supply_snapshot_max_age_seconds, ) +from .account_work_queue import STALE_RUNNING_SECONDS from .external_order_source import get_cross_db_lookup_counts TREND_DAYS = 7 @@ -495,6 +496,15 @@ def account_platform_status( bucket[str(status)] = int(count or 0) if status == "pending": bucket["oldest_pending_due_at"] = oldest_due + if isinstance(oldest_due, datetime): + due_utc = ( + oldest_due.replace(tzinfo=UTC) + if oldest_due.tzinfo is None + else oldest_due.astimezone(UTC) + ) + bucket["oldest_pending_age_seconds"] = max( + 0, int((moment - due_utc).total_seconds()) + ) sync_domains: dict[str, dict[str, Any]] = {} if include_diagnostics: @@ -664,6 +674,29 @@ def account_platform_status( "message": f"账号内部工作队列有 {overdue_work} 项待处理已过期", } ) + stale_running_work = int( + db.query(func.count(AccountWorkItem.id)) + .filter( + AccountWorkItem.status == "running", + AccountWorkItem.started_at.isnot(None), + AccountWorkItem.started_at + <= moment - timedelta(seconds=STALE_RUNNING_SECONDS), + ) + .scalar() + or 0 + ) + if stale_running_work: + alerts.append( + { + "code": "account_work_stale_running", + "severity": "warning", + "count": stale_running_work, + "message": ( + f"账号内部工作队列有 {stale_running_work} 项运行超过 " + f"{STALE_RUNNING_SECONDS // 60} 分钟未结束" + ), + } + ) trends = _platform_trends(db, moment) if include_trends else None if trends is not None: diff --git a/web/backend/services/account_sync_runner.py b/web/backend/services/account_sync_runner.py index 3cc9520..243ca0c 100644 --- a/web/backend/services/account_sync_runner.py +++ b/web/backend/services/account_sync_runner.py @@ -111,11 +111,16 @@ def _execute_storehome_sync( if not manual_id: raise RuntimeError("未配置精英宝典 manualID") client = client_factory(account.cookie) - snapshot = snapshot_fetcher( - client, - manual_id=manual_id, - rid=rid, - ) + try: + snapshot = snapshot_fetcher( + client, + manual_id=manual_id, + rid=rid, + ) + finally: + close = getattr(client, "close", None) + if callable(close): + close() result = sync_storehome_snapshot( db, account, @@ -211,13 +216,18 @@ def _execute_profile_sync( ) config = ensure_douyu_config(db) client = client_factory(account.cookie) - probe = probe_fetcher( - account, - config, - client=client, - session_checker=None, - **_profile_probe_kwargs(item.work_type, config), - ) + try: + probe = probe_fetcher( + account, + config, + client=client, + session_checker=None, + **_profile_probe_kwargs(item.work_type, config), + ) + finally: + close = getattr(client, "close", None) + if callable(close): + close() errors = probe.get("errors") or {} domain_error = { WORK_POINTS_SYNC: "points", @@ -269,13 +279,19 @@ def _execute_exchange_records_sync( session_checker=session_checker, ) config = ensure_douyu_config(db) - result = sync_exchange_records( - db, - account, - client_factory(account.cookie), - config_mapping(config), - source=f"account_work.{item.work_type}", - ) + client = client_factory(account.cookie) + try: + result = sync_exchange_records( + db, + account, + client, + config_mapping(config), + source=f"account_work.{item.work_type}", + ) + finally: + close = getattr(client, "close", None) + if callable(close): + close() return { "ok": True, "work_id": int(item.id), diff --git a/web/backend/services/account_sync_service.py b/web/backend/services/account_sync_service.py index ccddd78..7f13242 100644 --- a/web/backend/services/account_sync_service.py +++ b/web/backend/services/account_sync_service.py @@ -98,6 +98,18 @@ def is_domain_fresh( ) +def lock_account_row(db: Session, account_id: int | None) -> None: + """写账号派生表前先对账号主键加 X 锁,避免子表外键 S 锁与后续 UPDATE accounts 互锁成死锁。""" + if not account_id: + return + ( + db.query(Account.id) + .filter(Account.id == int(account_id)) + .with_for_update() + .first() + ) + + def _get_or_create_state( db: Session, *, @@ -105,11 +117,15 @@ def _get_or_create_state( domain: str, platform: str = "douyu", ) -> AccountSyncState: - state = get_sync_state( - db, - account_id=account_id, - domain=domain, - platform=platform, + state = ( + db.query(AccountSyncState) + .filter( + AccountSyncState.account_id == account_id, + AccountSyncState.platform == platform, + AccountSyncState.domain == domain, + ) + .with_for_update() + .first() ) if state is None: state = AccountSyncState( @@ -129,6 +145,7 @@ def mark_domain_dirty( domain: str, reason: str = "", ) -> AccountSyncState: + lock_account_row(db, account_id) state = _get_or_create_state(db, account_id=account_id, domain=domain) state.status = "dirty" state.valid_until = None @@ -148,6 +165,7 @@ def start_sync_run( source: str, task_id: int | None = None, ) -> AccountSyncRun: + lock_account_row(db, account_id) moment = datetime.now(UTC) state = _get_or_create_state(db, account_id=account_id, domain=domain) state.last_attempt_at = moment @@ -322,25 +340,51 @@ def record_sync_success( ) -> StorehomeSyncResult: """登记一次已经完成的官方查询投影。 - 适用于探针已经拿到并完成归一化的结果,避免调用方为了同步记录再重复请求。 + 适用于探针已经拿到并完成归一化的结果,避免调用方为了同步记录再重复请求, + 也避免同一次查询把 account_sync_states 先改成 running 再改成 success 的双倍锁更新。 """ - moment = observed_at or datetime.now(UTC) - run = start_sync_run( - db, + lock_account_row(db, account_id) + now = datetime.now(UTC) + moment = observed_at or now + ttl_seconds = max( + 1, + int( + valid_for_seconds + if valid_for_seconds is not None + else capability_ttl_seconds() + ), + ) + state = _get_or_create_state(db, account_id=account_id, domain=domain) + state.last_attempt_at = now + state.last_success_at = now + state.status = "success" + state.valid_until = now + timedelta(seconds=ttl_seconds) + state.next_retry_at = state.valid_until + state.error_code = "" + state.error_message = "" + state.source = source[:32] + if raw_payload is not None: + safe_payload = _json_safe(raw_payload) + state.raw_payload_json = safe_payload + state.payload_hash = _payload_hash(safe_payload) + state.state_version = int(state.state_version or 0) + 1 + + run = AccountSyncRun( account_id=account_id, + platform="douyu", domain=domain, - source=source, task_id=task_id, + started_at=now, + finished_at=now, + status="success", + source=source[:32], + item_count=int(item_count), + changed_count=int(changed_count), + duration_ms=0, + official_observed_at=moment, ) - finish_sync_success( - db, - run, - item_count=item_count, - changed_count=changed_count, - observed_at=moment, - raw_payload=raw_payload, - valid_for_seconds=valid_for_seconds, - ) + db.add(run) + db.flush() return StorehomeSyncResult( item_count=int(item_count), changed_count=int(changed_count), diff --git a/web/backend/services/account_work_queue.py b/web/backend/services/account_work_queue.py index c2c4e9c..7fc0d5f 100644 --- a/web/backend/services/account_work_queue.py +++ b/web/backend/services/account_work_queue.py @@ -5,13 +5,14 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import Any -from sqlalchemy import case, func, select +from sqlalchemy import case, func, or_, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from ..models import Account, AccountWorkItem WORK_AGING_SECONDS = 30 * 60 +STALE_RUNNING_SECONDS = 30 * 60 #: 供给补货任务的 reason 前缀;队列靠它给通用供给保留固定处理配额。 SUPPLY_REASON_PREFIX = "供给短缺:" @@ -293,6 +294,54 @@ def recover_running_account_work( return len(items) +def _stale_running_seconds(override: int | None = None) -> int: + import os + + if override is not None: + return max(60, int(override)) + try: + return max( + 60, + int(os.getenv("ACCOUNT_WORK_STALE_RUNNING_SECONDS", str(STALE_RUNNING_SECONDS))), + ) + except ValueError: + return STALE_RUNNING_SECONDS + + +def recover_stale_running_account_work( + db: Session, + *, + work_types: tuple[str, ...] | None = None, + stale_seconds: int | None = None, + now: datetime | None = None, +) -> int: + """回收运行超时仍停留在 running 的工作项,防止单线程异常后永久占住队列去重键。""" + moment = (now or datetime.now(UTC)).replace(microsecond=0) + seconds = _stale_running_seconds(stale_seconds) + cutoff = moment - timedelta(seconds=seconds) + query = db.query(AccountWorkItem).filter( + AccountWorkItem.status == "running", + or_( + AccountWorkItem.started_at <= cutoff, + (AccountWorkItem.started_at.is_(None) & (AccountWorkItem.updated_at <= cutoff)), + ), + ) + if work_types: + query = query.filter(AccountWorkItem.work_type.in_(work_types)) + items = query.all() + for item in items: + fail_account_work( + db, + item, + error=f"工作执行超过 {seconds // 60} 分钟未完成(疑似卡死),已回收", + retry_after_seconds=60, + now=moment, + ) + if items: + db.flush() + return len(items) + + def expire_stale_login_work( db: Session, *, @@ -398,6 +447,7 @@ def fail_account_work_type( __all__ = [ + "STALE_RUNNING_SECONDS", "active_account_work_count", "active_account_work_exists", "claim_account_work", @@ -407,5 +457,6 @@ __all__ = [ "fail_account_work", "fail_account_work_type", "recover_running_account_work", + "recover_stale_running_account_work", "reschedule_account_work_type", ] diff --git a/web/backend/services/automation/jobs/account_sync_queue.py b/web/backend/services/automation/jobs/account_sync_queue.py index 26bab5d..9bd713c 100644 --- a/web/backend/services/automation/jobs/account_sync_queue.py +++ b/web/backend/services/automation/jobs/account_sync_queue.py @@ -9,7 +9,10 @@ from sqlalchemy.orm import Session from ....models import AccountWorkItem, AutomationJob from ...account_sync_runner import ACCOUNT_SYNC_WORK_TYPES, run_account_sync_queue -from ...account_work_queue import expire_stale_login_work +from ...account_work_queue import ( + expire_stale_login_work, + recover_stale_running_account_work, +) JOB_KEY = "account_sync_queue" @@ -34,7 +37,12 @@ def run_account_sync_queue_job( ) -> dict[str, Any]: moment = datetime.now(UTC) expired = expire_stale_login_work(db, now=moment) - if expired: + recovered_stale = recover_stale_running_account_work( + db, + work_types=ACCOUNT_SYNC_WORK_TYPES, + now=moment, + ) + if expired or recovered_stale: db.commit() result = run_account_sync_queue( db, @@ -42,11 +50,16 @@ def run_account_sync_queue_job( ) if result.get("scanned"): result["remaining"] = count_pending_work(db) + notes: list[str] = [] + if recovered_stale: + result["recovered_stale"] = recovered_stale + notes.append(f"回收卡死工作 {recovered_stale} 条") if expired: result["expired_login"] = expired + notes.append(f"过期重登转人工 {expired} 条") + if notes: result["message"] = ( - f"{result.get('message') or '账号同步完成'}," - f"过期重登转人工 {expired} 条" + f"{result.get('message') or '账号同步完成'}," + ",".join(notes) ) return result diff --git a/web/backend/services/automation/jobs/douyu_tasks_retention.py b/web/backend/services/automation/jobs/douyu_tasks_retention.py index 5ee1e1e..3e266d4 100644 --- a/web/backend/services/automation/jobs/douyu_tasks_retention.py +++ b/web/backend/services/automation/jobs/douyu_tasks_retention.py @@ -48,7 +48,13 @@ from loguru import logger from sqlalchemy import and_, or_ from sqlalchemy.orm import Session -from ....models import AutomationJob, DouyuTask, ExecutionJob, ExecutionJobEvent +from ....models import ( + AccountSyncRun, + AutomationJob, + DouyuTask, + ExecutionJob, + ExecutionJobEvent, +) JOB_KEY = "douyu_tasks_retention" @@ -74,6 +80,7 @@ NOISE_TASK_TYPES: tuple[str, ...] = ( DEFAULT_NOISE_DAYS = 7 DEFAULT_BUSINESS_DAYS = 90 +DEFAULT_SYNC_RUN_DAYS = 14 DEFAULT_BATCH = 2000 DEFAULT_MAX_BATCHES = 50 @@ -167,10 +174,50 @@ def _delete_batch( return deleted, candidates[-1].created_at, ids[-1] +def _delete_sync_run_batch( + db: Session, + *, + cutoff: datetime, + batch: int, + cursor_started_at: datetime | None = None, + cursor_id: int = 0, +) -> tuple[int, datetime | None, int]: + """按游标分批清理过期 `account_sync_runs`,避免全表长时间持锁。""" + query = db.query(AccountSyncRun.id, AccountSyncRun.started_at).filter( + AccountSyncRun.started_at < cutoff + ) + if cursor_started_at is not None: + query = query.filter( + or_( + AccountSyncRun.started_at > cursor_started_at, + and_( + AccountSyncRun.started_at == cursor_started_at, + AccountSyncRun.id > cursor_id, + ), + ) + ) + candidates = ( + query.order_by(AccountSyncRun.started_at.asc(), AccountSyncRun.id.asc()) + .limit(batch) + .all() + ) + if not candidates: + return 0, cursor_started_at, cursor_id + ids = [int(row.id) for row in candidates] + deleted = int( + db.query(AccountSyncRun) + .filter(AccountSyncRun.id.in_(ids)) + .delete(synchronize_session=False) + or 0 + ) + return deleted, candidates[-1].started_at, ids[-1] + + def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]: config = _load_config(job) noise_days = _positive_int(config.get("noise_days"), DEFAULT_NOISE_DAYS) business_days = _positive_int(config.get("business_days"), DEFAULT_BUSINESS_DAYS) + sync_run_days = _positive_int(config.get("sync_run_days"), DEFAULT_SYNC_RUN_DAYS) batch = _positive_int(job.batch_size, DEFAULT_BATCH) max_batches = _positive_int(config.get("max_batches"), DEFAULT_MAX_BATCHES) @@ -179,6 +226,7 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any] # 带 tzinfo 会被驱动按本地时区处理(参见设计文档里那次 8 小时偏移事故)。 noise_cutoff = (now - timedelta(days=noise_days)).replace(tzinfo=None) business_cutoff = (now - timedelta(days=business_days)).replace(tzinfo=None) + sync_run_cutoff = (now - timedelta(days=sync_run_days)).replace(tzinfo=None) total_deleted = 0 batches = 0 @@ -259,6 +307,27 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any] batches += 1 db.commit() + deleted_sync_runs = 0 + sync_run_cursor_started_at: datetime | None = None + sync_run_cursor_id = 0 + while batches < max_batches: + deleted_runs, sync_run_cursor_started_at, sync_run_cursor_id = ( + _delete_sync_run_batch( + db, + cutoff=sync_run_cutoff, + batch=batch, + cursor_started_at=sync_run_cursor_started_at, + cursor_id=sync_run_cursor_id, + ) + ) + if deleted_runs <= 0: + break + batches += 1 + deleted_sync_runs += deleted_runs + db.commit() + if deleted_runs < batch: + break + # 注意措辞:这只说明「批次预算用光了」,**不等于**「确实还有积压」—— # 预算在上一档用完时,下一档根本没轮到执行,这里无法区分「没得删」和「没轮到」。 # 所以做成提示而非结论,措辞上也别谎称「仍有积压」。 @@ -283,9 +352,11 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any] "deleted_rest": per_pass.get("rest", 0), "deleted_execution_events": deleted_execution_events, "deleted_execution_jobs": deleted_execution_jobs, + "deleted_sync_runs": deleted_sync_runs, "batches": batches, "noise_days": noise_days, "business_days": business_days, + "sync_run_days": sync_run_days, "batch_budget_exhausted": batch_budget_exhausted, "message": message, } diff --git a/web/backend/services/automation/scheduler.py b/web/backend/services/automation/scheduler.py index 8a4d37e..5fe7885 100644 --- a/web/backend/services/automation/scheduler.py +++ b/web/backend/services/automation/scheduler.py @@ -473,10 +473,13 @@ def stop_scheduler() -> None: def scheduler_status() -> dict[str, Any]: + with _IN_FLIGHT_LOCK: + in_flight = sorted(_IN_FLIGHT) return { "enabled": automation_enabled(), "running": _thread is not None and _thread.is_alive(), "tick_seconds": TICK_SECONDS, "job_interval_seconds": JOB_INTERVAL_SECONDS, "registered": sorted(_REGISTRY), + "in_flight": in_flight, } diff --git a/web/backend/services/binding_poll_scheduler.py b/web/backend/services/binding_poll_scheduler.py index 7c7f8e1..59bcf3a 100644 --- a/web/backend/services/binding_poll_scheduler.py +++ b/web/backend/services/binding_poll_scheduler.py @@ -24,6 +24,17 @@ _thread: threading.Thread | None = None _lock = threading.Lock() _in_flight: set[int] = set() _in_flight_lock = threading.Lock() +_metrics_lock = threading.Lock() +_metrics: dict[str, object] = { + "last_tick_at": None, + "last_dispatched_at": None, + "last_claimed": 0, + "last_submitted": 0, + "total_dispatched": 0, + "consecutive_errors": 0, + "last_error": None, + "last_error_at": None, +} def _env_int(name: str, default: int, minimum: int, maximum: int) -> int: @@ -128,6 +139,9 @@ def _release_callback(_future: Future) -> None: def run_binding_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int: capacity = available_slots(TaskLane.BINDING_POLL) if capacity <= 0: + with _metrics_lock: + _metrics["last_claimed"] = 0 + _metrics["last_submitted"] = 0 return 0 claimed = _claim_due_binding_tasks(min(max(1, limit), capacity)) submitted = 0 @@ -144,6 +158,12 @@ def run_binding_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int: break future.add_done_callback(_release_callback) submitted += 1 + with _metrics_lock: + _metrics["last_claimed"] = len(claimed) + _metrics["last_submitted"] = submitted + if submitted: + _metrics["total_dispatched"] = int(_metrics["total_dispatched"] or 0) + submitted + _metrics["last_dispatched_at"] = datetime.now(UTC).isoformat() return submitted @@ -155,6 +175,9 @@ def _run() -> None: 30, ) while not _stop_event.is_set(): + now_iso = datetime.now(UTC).isoformat() + with _metrics_lock: + _metrics["last_tick_at"] = now_iso try: batch_size = _env_int( "BINDING_POLL_DISPATCH_BATCH", @@ -163,7 +186,15 @@ def _run() -> None: 200, ) run_binding_poll_dispatch_once(batch_size) + with _metrics_lock: + _metrics["consecutive_errors"] = 0 except Exception as exc: # noqa: BLE001 - scheduler must survive one bad tick + with _metrics_lock: + _metrics["consecutive_errors"] = ( + int(_metrics["consecutive_errors"] or 0) + 1 + ) + _metrics["last_error"] = f"{type(exc).__name__}: {exc}"[:500] + _metrics["last_error_at"] = now_iso logger.warning("绑定扫码调度轮次失败: {}", exc) _stop_event.wait(interval) @@ -199,10 +230,13 @@ def scheduler_status() -> dict[str, object]: running = _thread is not None and _thread.is_alive() with _in_flight_lock: in_flight = len(_in_flight) + with _metrics_lock: + metrics = dict(_metrics) return { "running": running, "in_flight": in_flight, "claim_seconds": CLAIM_SECONDS, + **metrics, } diff --git a/web/backend/services/douyu_account_probe.py b/web/backend/services/douyu_account_probe.py index c579c0b..efad1fd 100644 --- a/web/backend/services/douyu_account_probe.py +++ b/web/backend/services/douyu_account_probe.py @@ -47,6 +47,7 @@ from .account_sync_service import ( DOMAIN_POINTS, DOMAIN_ROLE, DOMAIN_SESSION, + lock_account_row, record_sync_success, ) from .cookie_check_service import check_douyu_cookie, classify_douyu_cookie_result @@ -755,6 +756,7 @@ def probe_account( cookie = str(account.cookie or "").strip() checked_at = _now() errors: dict[str, str] = {} + owns_client = client is None active_client = client or activity_client( cookie, logger_callback=logger_callback @@ -764,6 +766,57 @@ def probe_account( ) ), ) + try: + return _probe_account_with_client( + account, + config_info, + active_client=active_client, + cookie=cookie, + checked_at=checked_at, + errors=errors, + session_checker=session_checker, + with_elite=with_elite, + with_esports=with_esports, + with_storehome=with_storehome, + with_eligibility=with_eligibility, + with_limited_goods=with_limited_goods, + with_gold=with_gold, + with_goods=with_goods, + with_elite_role=with_elite_role, + include_esports=include_esports, + include_peace=include_peace, + use_cache=use_cache, + cache_key=cache_key, + ) + finally: + if owns_client: + close = getattr(active_client, "close", None) + if callable(close): + close() + + +def _probe_account_with_client( + account: Account, + config_info: dict[str, Any], + *, + active_client: DouyuActivityClient, + cookie: str, + checked_at: datetime, + errors: dict[str, str], + session_checker: Any, + with_elite: bool, + with_esports: bool, + with_storehome: bool, + with_eligibility: bool, + with_limited_goods: bool, + with_gold: bool, + with_goods: bool, + with_elite_role: bool, + include_esports: bool, + include_peace: bool, + use_cache: bool, + cache_key: str, +) -> dict[str, Any]: if session_checker is _DEFAULT_SESSION_CHECKER: session_checker = check_douyu_cookie session = ( @@ -1121,6 +1174,9 @@ def persist_probe_result( ) -> None: """把一次探针结果写回账号和生命周期,是账号能力的唯一落库入口。""" now = _now() + if account.id is not None: + # 严格先锁 accounts 主行,再写 account_sync_states / account_sync_runs / account_events + lock_account_row(db, int(account.id)) identity = probe.get("identity") or {} if identity.get("uid"): account.uid = str(identity["uid"])[:32] diff --git a/web/backend/services/douyu_batch_launcher.py b/web/backend/services/douyu_batch_launcher.py index 6f2dd5d..3e0ead0 100644 --- a/web/backend/services/douyu_batch_launcher.py +++ b/web/backend/services/douyu_batch_launcher.py @@ -54,6 +54,7 @@ def _run_batch( douyu_batch_registry.register(batch_id, log_queue, loop, runner) runner.run() finally: + douyu_batch_registry.mark_finished(batch_id) thread_db.close() diff --git a/web/backend/services/douyu_collab_catalog.py b/web/backend/services/douyu_collab_catalog.py index c197dac..d4f63b4 100644 --- a/web/backend/services/douyu_collab_catalog.py +++ b/web/backend/services/douyu_collab_catalog.py @@ -276,6 +276,7 @@ def refresh_activity_goods( ) if account is None: raise CollabError("没有带 CK 的斗鱼账号,无法刷新活动商品", code="no_account") + owns_client = client is None active_client = client or _client_for_account(account) config_info = config_mapping(config) db.expunge(account) @@ -316,6 +317,11 @@ def refresh_activity_goods( ) db.commit() raise + finally: + if owns_client: + close = getattr(active_client, "close", None) + if callable(close): + close() upsert_goods_snapshot(db, goods, commit=False) record_account_query( db, diff --git a/web/backend/services/douyu_collab_service.py b/web/backend/services/douyu_collab_service.py index 917df2e..869298f 100644 --- a/web/backend/services/douyu_collab_service.py +++ b/web/backend/services/douyu_collab_service.py @@ -25,6 +25,7 @@ from sqlalchemy.orm import Session from core.douyu import DouyuActivityClient +from ..database import release_idle_session from ..models import ( Account, AccountEvent, @@ -52,6 +53,7 @@ from .account_events_service import ( from .account_exchange_sync_service import sync_exchange_records from .account_query_filters import ACTIVE_COLLAB_STATUSES from .account_sync_runner import WORK_STOREHOME_SYNC +from .account_sync_service import lock_account_row from .account_work_queue import enqueue_account_work from .audit_service import record_account_action, record_audit from .binding_ownership import role_names_match @@ -203,6 +205,22 @@ from .platform_fulfillment.account_selector import ( ) +def _detached_account_snapshot(account: Account) -> Account: + """构造脱离 ORM 会话的轻量账号快照,供无数据库连接的外网探针读取。""" + return Account( + id=account.id, + uid=account.uid, + username=account.username, + nickname=account.nickname, + cookie=account.cookie, + elite_opened=account.elite_opened, + esports_opened=account.esports_opened, + points=account.points, + points_expire_at=account.points_expire_at, + gold_balance=account.gold_balance, + ) + + def _probe_with_client( account: Account, *, @@ -235,15 +253,21 @@ def _probe_with_client( "legacy_act_alias": legacy_act_alias, } ) - result = probe_account( - account, - config_info, - client=active_client, - session_checker=None if caller_supplied_client else check_douyu_cookie, - with_gold=True, - with_goods=with_goods, - use_cache=not caller_supplied_client, - ) + try: + result = probe_account( + account, + config_info, + client=active_client, + session_checker=None if caller_supplied_client else check_douyu_cookie, + with_gold=True, + with_goods=with_goods, + use_cache=not caller_supplied_client, + ) + finally: + if not caller_supplied_client and isinstance( + active_client, DouyuActivityClient + ): + active_client.close() elite = result.get("elite") or {} role = (result.get("roles") or {}).get("elite") or {} identity = result.get("identity") or {} @@ -1043,6 +1067,7 @@ def update_order( client=client, with_goods=True, ) + lock_account_row(db, int(account.id)) _ensure_order_account_lease( db, current, @@ -1137,17 +1162,31 @@ def set_account( if account is None: raise CollabError("斗鱼账号不存在", code="account_not_found") previous_account_id = int(order.account_id or 0) + order_id = int(order.id) + account_id = int(account.id) + current_id = int(current.id) config = resolve_config(db) + manual_id = str(config.manual_id or "") + rid = str(config.rid or "") + bind_act_alias = str(config.bind_act_alias or "") + confirm_act_alias = str(config.confirm_act_alias or "") + legacy_act_alias = str(config.legacy_act_alias or "") + account_snapshot = _detached_account_snapshot(account) + release_idle_session(db) probe = _probe_with_client( - account, - manual_id=str(config.manual_id or ""), - rid=str(config.rid or ""), - act_alias=str(config.bind_act_alias or ""), - confirm_act_alias=str(config.confirm_act_alias or ""), - legacy_act_alias=str(config.legacy_act_alias or ""), + account_snapshot, + manual_id=manual_id, + rid=rid, + act_alias=bind_act_alias, + confirm_act_alias=confirm_act_alias, + legacy_act_alias=legacy_act_alias, client=client, with_goods=True, ) + order = db.get(DouyuExternalOrder, order_id) or order + account = db.get(Account, account_id) or account + current = db.get(User, current_id) or current + lock_account_row(db, int(account.id)) _ensure_order_account_lease( db, current, @@ -1208,17 +1247,36 @@ def verify_order( ) if account is None: raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found") + order_id = int(order.id) + account_id = int(account.id) + current_id = int(current.id) config = resolve_config(db) + manual_id = str(config.manual_id or "") + rid = str(config.rid or "") + bind_act_alias = str(config.bind_act_alias or "") + confirm_act_alias = str(config.confirm_act_alias or "") + legacy_act_alias = str(config.legacy_act_alias or "") + account_snapshot = _detached_account_snapshot(account) + release_idle_session(db) probe = _probe_with_client( - account, - manual_id=str(config.manual_id or ""), - rid=str(config.rid or ""), - act_alias=str(config.bind_act_alias or ""), - confirm_act_alias=str(config.confirm_act_alias or ""), - legacy_act_alias=str(config.legacy_act_alias or ""), + account_snapshot, + manual_id=manual_id, + rid=rid, + act_alias=bind_act_alias, + confirm_act_alias=confirm_act_alias, + legacy_act_alias=legacy_act_alias, client=client, with_goods=True, ) + reloaded_order = db.get(DouyuExternalOrder, order_id) + if reloaded_order is None: + raise CollabError("订单不存在", status_code=404, code="order_not_found") + reloaded_account = db.get(Account, account_id) + if reloaded_account is None: + raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found") + order = reloaded_order + account = reloaded_account + current = db.get(User, current_id) or current apply_probe_snapshot( db, current, @@ -1757,11 +1815,19 @@ def list_order_exchange_records( error_text = "" if refresh: + order_id = int(order.id) + account_id = int(account.id) + current_id = int(current.id) try: raw_records = _load_exchange_records_for_orders(db, [order], client=client) synced_at = _now() except Exception as exc: # noqa: BLE001 error_text = str(exc) + order = db.get(DouyuExternalOrder, order_id) or order + account = db.get(Account, account_id) or account + current = db.get(User, current_id) or current + if account.id is not None: + lock_account_row(db, int(account.id)) record_account_query( db, account, @@ -1864,18 +1930,22 @@ def _load_exchange_records_for_orders( ) if account is None: raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found") - config = resolve_config(db) - active_client = client or _client_for_account(account) - result = sync_exchange_records( - db, - account, - active_client, - config_mapping(config), - source="douyu_collab.activity", - scopes=("elite",), - limit=ACTIVITY_RECORD_FETCH_LIMIT, - max_pages=ACTIVITY_RECORD_MAX_PAGES, - ) + config_map = config_mapping(resolve_config(db)) + active_client = client or _client_for_account(_detached_account_snapshot(account)) + try: + result = sync_exchange_records( + db, + account, + active_client, + config_map, + source="douyu_collab.activity", + scopes=("elite",), + limit=ACTIVITY_RECORD_FETCH_LIMIT, + max_pages=ACTIVITY_RECORD_MAX_PAGES, + ) + finally: + if client is None and isinstance(active_client, DouyuActivityClient): + active_client.close() return [ dict(record) for record in (result.get("records") or {}).get("elite", []) @@ -1901,6 +1971,9 @@ def query_activity( ) if account is None: raise CollabError("订单关联的斗鱼账号不存在", code="account_not_found") + order_id = int(order.id) + account_id = int(account.id) + current_id = int(current.id) errors: list[str] = [] probe: dict[str, Any] = {} loaded_records: list[dict[str, Any]] = [] @@ -1912,8 +1985,13 @@ def query_activity( ) except Exception as exc: # noqa: BLE001 errors.append(f"兑换记录: {exc}") + order = db.get(DouyuExternalOrder, order_id) or order + account = db.get(Account, account_id) or account + current = db.get(User, current_id) or current else: loaded_records = [dict(record) for record in records] + if account.id is not None: + lock_account_row(db, int(account.id)) if record_query_error: errors.append(f"兑换记录: {record_query_error}") manual_score = _to_int(order.points_balance) @@ -1924,16 +2002,26 @@ def query_activity( points_message = _text(order.points_check_message) threshold = normalize_threshold(order.points_threshold) else: - config = resolve_config(db) - active_client = client or _client_for_account(account) - probe = probe_account( - account, - config, - client=active_client, - session_checker=None, - with_gold=True, - with_elite_role=False, - ) + config_map = config_mapping(resolve_config(db)) + account_snapshot = _detached_account_snapshot(account) + active_client = client or _client_for_account(account_snapshot) + release_idle_session(db) + try: + probe = probe_account( + account_snapshot, + config_map, + client=active_client, + session_checker=None, + with_gold=True, + with_elite_role=False, + ) + finally: + if client is None and isinstance(active_client, DouyuActivityClient): + active_client.close() + order = db.get(DouyuExternalOrder, order_id) or order + account = db.get(Account, account_id) or account + current = db.get(User, current_id) or current + lock_account_row(db, int(account.id)) elite = (probe.get("elite") or {}).get("raw") or {} gold = { "gold": (probe.get("gold") or {}).get("balance"), @@ -2187,11 +2275,16 @@ def query_activity_batch( _load_exchange_records_for_orders(db, account_orders), "", ) + if (db.info or {}).get("managed_request_session"): + # 逐账号持久化官方同步快照并归还连接,避免下一个账号拉取期间占着事务 + db.commit() except Exception as exc: # noqa: BLE001 - 账号级错误复用到同账号订单 + db.rollback() records_by_account[account_key] = ([], str(exc)) results: list[dict[str, Any]] = [] for order in orders: + order = db.get(DouyuExternalOrder, int(order.id)) or order if order.account_id: account_key = ("id", int(order.account_id)) else: diff --git a/web/backend/services/douyu_runner.py b/web/backend/services/douyu_runner.py index d753a00..64e390e 100644 --- a/web/backend/services/douyu_runner.py +++ b/web/backend/services/douyu_runner.py @@ -9,12 +9,13 @@ from sqlalchemy.orm import joinedload from core.douyu import DouyuActivityError -from ..database import WorkerSessionLocal +from ..database import WorkerSessionLocal, release_idle_session from ..models import DouyuTask from .cookie_check_service import check_douyu_cookie -from .douyu_account_probe import verify_account_session +from .douyu_account_probe import persist_probe_result, probe_session from .douyu_runner_bind import BindMixin -from .douyu_runner_core import ( # noqa: F401 (douyu_batch_registry 供 routers 重导出) +from .douyu_runner_core import ( + DOUYU_PROXY_TASK_TYPES, DouyuBatchRunnerCore, douyu_batch_registry, ) @@ -62,35 +63,39 @@ class DouyuBatchRunner( result, ) return - if task.task_type == "create_gold_qr": - if str(result.get("recharge_channel") or "") == "supplier_api": - amount = int( - result.get("buy_num") - or self._task_payload(task).get("amount") - or self._task_payload(task).get("gold_amount") - or 1 - ) - self._poll_create_gold_supplier_once( + previous_clients = self._begin_client_tracking() + try: + if task.task_type == "create_gold_qr": + if str(result.get("recharge_channel") or "") == "supplier_api": + amount = int( + result.get("buy_num") + or self._task_payload(task).get("amount") + or self._task_payload(task).get("gold_amount") + or 1 + ) + self._poll_create_gold_supplier_once( + db, + task, + account, + cookie, + amount=amount, + ) + else: + self._poll_create_gold_qr_once(db, task, account, cookie, config) + elif task.task_type == "create_elite_qr": + self._poll_create_elite_qr_once(db, task, account, cookie, config) + elif task.task_type == "create_esports_qr": + self._poll_create_esports_qr_once(db, task, account, cookie, config) + else: + self._mark_task( db, task, - account, - cookie, - amount=amount, + "failed", + f"不支持的支付轮询任务: {task.task_type}", + result, ) - else: - self._poll_create_gold_qr_once(db, task, account, cookie, config) - elif task.task_type == "create_elite_qr": - self._poll_create_elite_qr_once(db, task, account, cookie, config) - elif task.task_type == "create_esports_qr": - self._poll_create_esports_qr_once(db, task, account, cookie, config) - else: - self._mark_task( - db, - task, - "failed", - f"不支持的支付轮询任务: {task.task_type}", - result, - ) + finally: + self._end_client_tracking(previous_clients) def mark_payment_poll_timeout(self, db, task: DouyuTask) -> None: result = dict(task.result or {}) @@ -105,7 +110,56 @@ class DouyuBatchRunner( self._execute_one_with_slot(task_id, config, total) def _execute_one_with_slot(self, task_id: int, config: dict, total: int): + with self._counter_lock: + self._task_started_at[int(task_id)] = time.monotonic() + # 阶段一:短事务抢占任务并标记 running,随后立即释放连接 + cookie = "" + task_type = "" + account_name = f"task#{task_id}" + current = 0 + preflight_db = SessionLocal() + try: + task = ( + preflight_db.query(DouyuTask) + .options(joinedload(DouyuTask.account)) + .filter(DouyuTask.id == task_id) + .first() + ) + if not task or self._stop.is_set(): + return + account = task.account + account_name = self._account_name(account) + task_type = str(task.task_type or "") + self._update_task_progress(preflight_db, task, "running", "执行中") + + with self._counter_lock: + self._started += 1 + current = self._started + + self._push_log("info", f"[{current}/{total}] 开始: {account_name}") + # CK 与健康状态都挂在账号上(2026-10-04 CK 解耦)。 + cookie = account.cookie or "" + if not cookie: + self._mark_task(preflight_db, task, "failed", "账号没有可用登录 Cookie") + self._push_log("warning", f"[{current}] {account_name} 无 Cookie") + return + finally: + preflight_db.close() + + # 阶段二:不持数据库连接做外网 CK 预检和代理探活 + cookie_check = probe_session(cookie, checker=check_douyu_cookie) + ck_verdict = str(cookie_check["status"]) + prefetched_proxies = ( + self._proxies_for_task() + if ck_verdict == "valid" and task_type in DOUYU_PROXY_TASK_TYPES + else None + ) + + # 阶段三:打开正式执行会话落库预检结论并执行任务处理 worker_db = SessionLocal() + task = None + if isinstance(getattr(worker_db, "info", None), dict): + worker_db.info["managed_worker_session"] = True try: task = ( worker_db.query(DouyuTask) @@ -116,33 +170,32 @@ class DouyuBatchRunner( if not task or self._stop.is_set(): return account = task.account - self._update_task_progress(worker_db, task, "running", "执行中") - - with self._counter_lock: - self._started += 1 - current = self._started - - self._push_log( - "info", f"[{current}/{total}] 开始: {self._account_name(account)}" - ) - # CK 与健康状态都挂在账号上(2026-10-04 CK 解耦)。 - cookie = account.cookie or "" - if not cookie: - self._mark_task(worker_db, task, "failed", "账号没有可用登录 Cookie") - self._push_log( - "warning", f"[{current}] {self._account_name(account)} 无 Cookie" - ) - return - - cookie_check = verify_account_session( + raw_detail = cookie_check.get("detail") + detail = raw_detail if isinstance(raw_detail, dict) else {} + persist_probe_result( worker_db, account, + { + "probe_id": f"douyu_task.preflight:{task_id}:{account.id or 0}", + "identity": { + "uid": account.uid, + "username": account.username, + "nickname": detail.get("nickname") or "", + "nickname_source": "session", + }, + "session": cookie_check, + "elite": {}, + "eligibility": {}, + "roles": {}, + "gold": {}, + "goods": {}, + "errors": {}, + }, source="douyu_task.preflight", - checker=check_douyu_cookie, record_event=False, commit=True, + update_session=True, ) - ck_verdict = str(cookie_check["status"]) if ck_verdict != "valid": prefix = ( "Cookie 已失效,请重新登录" @@ -157,6 +210,8 @@ class DouyuBatchRunner( return update_account_profile_from_cookie(account, cookie) + if worker_db.dirty or worker_db.new or worker_db.deleted: + worker_db.commit() handler = { "refresh_esports_goods": self._execute_refresh_esports_goods, @@ -199,19 +254,34 @@ class DouyuBatchRunner( self._mark_task(worker_db, task, "failed", "不支持的任务类型") return - handler(worker_db, task, account, cookie, config) + self._hook_local.prefetched_proxies = prefetched_proxies + self._hook_local.has_prefetched_proxies = ( + ck_verdict == "valid" and task_type in DOUYU_PROXY_TASK_TYPES + ) + previous_clients = self._begin_client_tracking() + try: + handler(worker_db, task, account, cookie, config) + finally: + self._end_client_tracking(previous_clients) + self._hook_local.has_prefetched_proxies = False + self._hook_local.prefetched_proxies = None + task = worker_db.get(DouyuTask, task_id) or task + account = task.account self._push_log( "success", f"[{current}] {self._account_name(account)} {task.message}" ) except DouyuActivityError as exc: - if "task" in locals() and task: - self._mark_task(worker_db, task, "failed", str(exc)) + active_task = (worker_db.get(DouyuTask, task_id) or task) if task else None + if active_task is not None: + self._mark_task(worker_db, active_task, "failed", str(exc)) self._push_log("warning", f"斗鱼任务失败: {exc}") except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 - if "task" in locals() and task: - self._mark_task(worker_db, task, "error", str(exc)) + active_task = (worker_db.get(DouyuTask, task_id) or task) if task else None + if active_task is not None: + self._mark_task(worker_db, active_task, "error", str(exc)) self._push_log("error", f"斗鱼任务异常: {exc}") finally: + release_idle_session(worker_db) worker_db.close() def run(self): @@ -265,7 +335,7 @@ class DouyuBatchRunner( ) if future is None: break - pending[future] = (int(task.id), time.monotonic()) + pending[future] = (int(task_id), time.monotonic()) next_index += 1 if not pending: @@ -277,6 +347,7 @@ class DouyuBatchRunner( continue for future in completed: task_id, submitted_at = pending.pop(future) + started_at = self._task_started_at.pop(int(task_id), None) try: future.result() except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 @@ -285,7 +356,11 @@ class DouyuBatchRunner( f"Worker 异常 task_id={task_id}: {exc}", ) else: - waited = time.monotonic() - submitted_at + waited = ( + max(0.0, started_at - submitted_at) + if started_at is not None + else 0.0 + ) if waited >= 5: self._push_log( "info", @@ -298,5 +373,6 @@ class DouyuBatchRunner( self._push_log("info", f"斗鱼任务批次 {self.batch_id} 完成") self._push_log("result", "") finally: + douyu_batch_registry.mark_finished(self.batch_id) if getattr(self, "close_db", True): self.db.close() diff --git a/web/backend/services/douyu_runner_core.py b/web/backend/services/douyu_runner_core.py index 761c8bc..80d4dfa 100644 --- a/web/backend/services/douyu_runner_core.py +++ b/web/backend/services/douyu_runner_core.py @@ -131,6 +131,7 @@ class DouyuBatchRunnerCore: self._stop = threading.Event() self._counter_lock = threading.Lock() self._hook_local = threading.local() + self._task_started_at: dict[int, float] = {} self._started = 0 # 代理接入 (配置源 = 代理配置页, 与 CK 检测/虎牙注册同款): # 仅兑换/锁单/支付/充值/送礼等写操作任务走代理, 查询/刷新/绑定类直连 @@ -162,6 +163,11 @@ class DouyuBatchRunnerCore: 写/读分离:仅兑换/锁单/支付/开通/充值/送礼等写操作任务走代理(应对 IP 频控); 查询/刷新/绑定/扫码等读操作任务始终直连,不消耗代理额度。 """ + if getattr(self._hook_local, "has_prefetched_proxies", False): + self._hook_local.has_prefetched_proxies = False + prefetched = getattr(self._hook_local, "prefetched_proxies", None) + self._hook_local.prefetched_proxies = None + return prefetched if self.task_type not in DOUYU_PROXY_TASK_TYPES: return None if self._static_proxies: @@ -615,6 +621,30 @@ class DouyuBatchRunnerCore: payload = payload_raw if isinstance(payload_raw, dict) else {} return {**payload, **self.payload} + def _track_client(self, client: DouyuActivityClient) -> DouyuActivityClient: + clients = getattr(self._hook_local, "clients", None) + if isinstance(clients, list): + clients.append(client) + return client + + def _begin_client_tracking(self) -> list[Any] | None: + previous = getattr(self._hook_local, "clients", None) + self._hook_local.clients = [] + return previous + + def _end_client_tracking(self, previous: list[Any] | None = None) -> None: + clients = getattr(self._hook_local, "clients", None) + self._hook_local.clients = previous + if not isinstance(clients, list): + return + for client in clients: + close = getattr(client, "close", None) + if callable(close): + try: + close() + except Exception: # noqa: BLE001 - 收尾清理不能覆盖主流程结果 + logger.debug("关闭 DouyuActivityClient 会话失败", exc_info=True) + def _client( self, cookie: str, @@ -623,10 +653,12 @@ class DouyuBatchRunnerCore: ) -> DouyuActivityClient: """任务 HTTP 客户端:写操作任务注入会话级代理(兑换/锁单/支付/充值/送礼), 读操作任务直连;持久支付轮询显式 ``direct=True``,不能每轮取新代理。""" - return activity_client( - cookie, - logger_callback=lambda msg: self._push_log("debug", msg), - proxies=None if direct else self._proxies_for_task(), + return self._track_client( + activity_client( + cookie, + logger_callback=lambda msg: self._push_log("debug", msg), + proxies=None if direct else self._proxies_for_task(), + ) ) def _sleep_interruptible(self, seconds: float) -> bool: @@ -641,11 +673,37 @@ class DouyuBatchRunnerCore: return not self._stop.is_set() +def _finished_batch_ttl_seconds() -> int: + import os + + raw = os.getenv("DOUYU_BATCH_REGISTRY_FINISHED_TTL_SECONDS", "600") + try: + return max(1, int(raw)) + except ValueError: + return 600 + + class DouyuBatchRegistry: - """管理运行中的斗鱼任务批次。""" + """管理运行中的斗鱼任务批次,并对已结束批次做 TTL 清理防止内存泄漏。""" def __init__(self): self._batches: dict[str, dict] = {} + self._lock = threading.RLock() + + def _prune_expired_locked(self, now: float | None = None) -> int: + cutoff = (time.time() if now is None else float(now)) - _finished_batch_ttl_seconds() + expired = [ + batch_id + for batch_id, info in self._batches.items() + if info.get("finished") and float(info.get("updated_at") or 0) <= cutoff + ] + for batch_id in expired: + self._batches.pop(batch_id, None) + return len(expired) + + def prune_expired(self, now: float | None = None) -> int: + with self._lock: + return self._prune_expired_locked(now=now) def register( self, @@ -654,31 +712,52 @@ class DouyuBatchRegistry: loop: asyncio.AbstractEventLoop | None, runner: DouyuBatchRunner, ): - self._batches[batch_id] = { - "log_queue": log_queue, - "loop": loop, - "runner": runner, - "finished": False, - "updated_at": time.time(), - } + with self._lock: + self._prune_expired_locked() + self._batches[batch_id] = { + "log_queue": log_queue, + "loop": loop, + "runner": runner, + "finished": False, + "updated_at": time.time(), + } def get(self, batch_id: str): - return self._batches.get(batch_id) + with self._lock: + return self._batches.get(batch_id) def pop(self, batch_id: str): - return self._batches.pop(batch_id, None) + with self._lock: + return self._batches.pop(batch_id, None) def mark_finished(self, batch_id: str): - if batch_id in self._batches: - self._batches[batch_id]["finished"] = True - self._batches[batch_id]["updated_at"] = time.time() + with self._lock: + if batch_id in self._batches: + self._batches[batch_id]["finished"] = True + self._batches[batch_id]["updated_at"] = time.time() + self._prune_expired_locked() def active_ids(self) -> set[str]: - return { - batch_id - for batch_id, info in self._batches.items() - if not info.get("finished") - } + with self._lock: + self._prune_expired_locked() + return { + batch_id + for batch_id, info in self._batches.items() + if not info.get("finished") + } + + def stats(self) -> dict[str, int]: + with self._lock: + self._prune_expired_locked() + active = sum( + 1 for info in self._batches.values() if not info.get("finished") + ) + total = len(self._batches) + return { + "active": active, + "finished": max(0, total - active), + "total": total, + } douyu_batch_registry = DouyuBatchRegistry() diff --git a/web/backend/services/douyu_runner_donate.py b/web/backend/services/douyu_runner_donate.py index 00f0029..e1970a8 100644 --- a/web/backend/services/douyu_runner_donate.py +++ b/web/backend/services/douyu_runner_donate.py @@ -10,6 +10,7 @@ from sqlalchemy.orm import Session from core.douyu import DouyuActivityClient from ..models import Account, DouyuTask +from .account_sync_service import lock_account_row from .business_events import record_gold_spent, record_points_credit from .douyu_activity_query import extract_points_expire_time, query_csrf @@ -196,6 +197,8 @@ class DonateMixin: message += f",电竞积分: {account.esports_points}" # 电竞礼物同样产生积分到账 —— 这一类此前**从来不在收集范围** # (不在 COLLECTED_TASK_TYPES 里),时间线上一直是空白。 + if account.id is not None: + lock_account_row(db, int(account.id)) record_points_credit( db, account, @@ -334,6 +337,8 @@ class DonateMixin: # 旧收集器把「预期涨幅」当既成事实写进台账(未确认时也记 +980), # 那是把预期记成到账。这里宁可标清楚,也不假装它是确认过的数字。 # 金额用本地可等价重算的值(1 个精英令 ≈ 10 分),不再依赖 result 里的字段。 + if account.id is not None: + lock_account_row(db, int(account.id)) record_points_credit( db, account, diff --git a/web/backend/services/douyu_runner_gold.py b/web/backend/services/douyu_runner_gold.py index 6fc2eec..f408f59 100644 --- a/web/backend/services/douyu_runner_gold.py +++ b/web/backend/services/douyu_runner_gold.py @@ -335,6 +335,7 @@ class GoldMixin: except Exception as exc: # noqa: BLE001 余额核对失败仍继续查供应商 gold_error = str(exc) + client = None try: client = FishFinRechargeClient(FishFinRechargeConfig.from_env()) payload = client.query_order(order_no) @@ -349,6 +350,11 @@ class GoldMixin: ) except Exception as exc: # noqa: BLE001 供应商查询异常由持久调度继续重试 supplier_error = str(exc) + finally: + if client is not None: + close = getattr(client, "close", None) + if callable(close): + close() # 查询期间供应商回调可能已经把任务收口。重新锁行后再决定是否写入, # 避免长时间 HTTP 调用结束后用旧状态覆盖回调结果。 @@ -667,17 +673,22 @@ class GoldMixin: ) client = FishFinRechargeClient(FishFinRechargeConfig.from_env(), trace=trace) - order_payload = client.create_order( - buy_num=amount, - pay_amount=pay_amount, - out_order_id=order_no, - product_id=product_id, - recharge_arg=[ - {"templateName": template_name, "templateVal": recharge_account} - ], - order_type=0, - notify_url=client.config.notify_url, - ) + try: + order_payload = client.create_order( + buy_num=amount, + pay_amount=pay_amount, + out_order_id=order_no, + product_id=product_id, + recharge_arg=[ + {"templateName": template_name, "templateVal": recharge_account} + ], + order_type=0, + notify_url=client.config.notify_url, + ) + finally: + close = getattr(client, "close", None) + if callable(close): + close() code = self._to_int(self._supplier_value(order_payload, "code")) status = self._supplier_order_status(order_payload) result = { diff --git a/web/backend/services/douyu_runner_goods.py b/web/backend/services/douyu_runner_goods.py index 7ff54c9..93020df 100644 --- a/web/backend/services/douyu_runner_goods.py +++ b/web/backend/services/douyu_runner_goods.py @@ -11,8 +11,10 @@ from sqlalchemy.orm import Session from core.douyu import DouyuActivityClient, DouyuActivityError +from ..database import release_idle_session from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask from .account_exchange_sync_service import sync_exchange_records +from .account_sync_service import lock_account_row from .binding_ownership import role_names_match, workbench_task_occupation_error from .business_events import record_exchange from .douyu_activity_query import ( @@ -279,6 +281,8 @@ class GoodsMixin: score = int(goods.score) * ( int(num) if isinstance(num, (int, float)) else 1 ) + if account.id is not None: + lock_account_row(db, int(account.id)) record_exchange( db, account, @@ -374,156 +378,148 @@ class GoodsMixin: if not commodity_id: self._mark_task(db, task, "failed", "请选择兑换商品") return - client = self._client(cookie) - manual_id = str(config["manual_id"]) - rid = str(config.get("rid") or "") - result: dict = {"commodity_id": commodity_id} - - # ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ---- - manual_type = None - try: - user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid) - manual_type = user_info.get("manual_type") - except DouyuActivityError as exc: - self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}") - detail = None - try: - detail = client.query_goods_detail( - manual_id=manual_id, commodity_id=commodity_id, rid=rid - )["detail"] - except DouyuActivityError as exc: - self._push_log("warning", f"查询商品详情失败,按经典流程继续: {exc}") - - batch_num_limit = None - if detail and int(detail.get("batchExchange") or 0) > 0: - try: - batch_num_limit = client.batch_exchange_limit( - manual_id=manual_id, commodity_id=commodity_id, rid=rid - )["limit"] - except DouyuActivityError as exc: - self._push_log("warning", f"查询批量兑换上限失败: {exc}") - - plan = DouyuActivityClient.resolve_exchange_plan( - detail or {}, manual_type=manual_type, batch_num_limit=batch_num_limit - ) - result["plan"] = plan - if detail: - result["detail"] = detail - action = plan["action"] - - def finish_failed(message: str) -> None: - self._mark_task( - db, - task, - "failed", - message, - {"commodity_id": commodity_id, "plan": plan, "detail": detail}, - ) - - if action in ("blocked", "wait"): - finish_failed(f"兑换失败: {plan['text']}") - return - goods = ( db.query(DouyuGoodsSnapshot) .filter(DouyuGoodsSnapshot.commodity_id == commodity_id) .first() ) + goods_raw = goods.raw if goods else None name = (goods.name if goods else "") or commodity_id - - if action == "subscribe": + task_id = int(task.id) + account_id = int(account.id) + created_by = int(task.created_by) + manual_id = str(config["manual_id"]) + rid = str(config.get("rid") or "") + result: dict[str, Any] = {"commodity_id": commodity_id} + client = self._client(cookie) + # 锁单、退避睡眠和支付轮询耗时可能高达数分钟,期间释放干净的托管连接。 + release_idle_session(db) + try: + # ---- 对齐浏览器:先查手册状态 + 商品详情,按页面状态机选兑换链路 ---- + manual_type = None try: - client.subscribe_commodity( - manual_id=manual_id, commodity_id=commodity_id - ) + user_info = query_elite_user_info(client, manual_id=manual_id, rid=rid) + manual_type = user_info.get("manual_type") except DouyuActivityError as exc: - finish_failed(f"预约到货失败: {exc}") - return - account.updated_at = datetime.now(UTC) - self._mark_task( - db, - task, - "success", - f"已预约到货: {name} ({plan['text']})", - {"commodity_id": commodity_id, "plan": plan, "detail": detail}, - ) - return - - if action == "pre_exchange": + self._push_log("warning", f"查询手册状态失败,按经典流程继续: {exc}") + detail = None try: - check = client.pre_exchange_check( - manual_id=manual_id, commodity_id=commodity_id - ) - user_status = int((check.get("data") or {}).get("userStatus") or 0) - if user_status == 1 and not plan["pre_exchange"]: - self._mark_task( - db, - task, - "success", - f"已预兑: {name},等待开放后继续兑换", - { - "commodity_id": commodity_id, - "plan": plan, - "detail": detail, - "check": check, - }, - ) - return - confirm = client.confirm_pre_exchange( + detail = client.query_goods_detail( manual_id=manual_id, commodity_id=commodity_id, rid=rid - ) + )["detail"] except DouyuActivityError as exc: - finish_failed(f"预兑失败: {exc}") + self._push_log("warning", f"查询商品详情失败,按经典流程继续: {exc}") + + batch_num_limit = None + if detail and int(detail.get("batchExchange") or 0) > 0: + try: + batch_num_limit = client.batch_exchange_limit( + manual_id=manual_id, commodity_id=commodity_id, rid=rid + )["limit"] + except DouyuActivityError as exc: + self._push_log("warning", f"查询批量兑换上限失败: {exc}") + + plan = DouyuActivityClient.resolve_exchange_plan( + detail or {}, manual_type=manual_type, batch_num_limit=batch_num_limit + ) + result["plan"] = plan + if detail: + result["detail"] = detail + action = plan["action"] + + def finish_failed(message: str) -> None: + active_task = db.get(DouyuTask, task_id) or task + self._mark_task( + db, + active_task, + "failed", + message, + {"commodity_id": commodity_id, "plan": plan, "detail": detail}, + ) + + if action in ("blocked", "wait"): + finish_failed(f"兑换失败: {plan['text']}") return - account.updated_at = datetime.now(UTC) - self._mark_task( - db, - task, - "success", - f"预兑成功: {name},开放后可继续兑换", - { - "commodity_id": commodity_id, - "plan": plan, - "detail": detail, - "check": check, - "confirm": confirm, - }, - ) - return - # ---- 经典链路:锁单 -> 人类节奏等待 -> 支付(错误分类退避重试)---- - try: - num = max(1, int(payload.get("num") or 1)) - except (TypeError, ValueError): - num = 1 - num = min(num, int(plan.get("max_num") or 1)) + if action == "subscribe": + try: + client.subscribe_commodity( + manual_id=manual_id, commodity_id=commodity_id + ) + except DouyuActivityError as exc: + finish_failed(f"预约到货失败: {exc}") + return + active_task = db.get(DouyuTask, task_id) or task + active_account = db.get(Account, account_id) or account + active_account.updated_at = datetime.now(UTC) + self._mark_task( + db, + active_task, + "success", + f"已预约到货: {name} ({plan['text']})", + {"commodity_id": commodity_id, "plan": plan, "detail": detail}, + ) + return - # 少量随机抖动(浏览器点击商品到锁单之间有人工间隔) - self._push_log("info", f" 兑换 {name}: {plan['text']}") - if not self._sleep_interruptible( - random.uniform(*DOUYU_EXCHANGE_PRE_CREATE_JITTER) - ): - self._mark_task(db, task, "stopped", "任务已停止", result) - return - try: - locked = client.create_exchange_order( - manual_id=manual_id, - rid=rid, - commodity_id=commodity_id, - num=num, - ) - except DouyuActivityError as exc: - # 锁单本身被频控时做一次长退避重试,避免无脑连打 - backoff = ( - DOUYU_EXCHANGE_RATE_LIMIT_BACKOFFS[0] - if self._is_rate_limited_error(str(exc)) - else 3 - ) - self._push_log( - "info", f" 锁定兑换商品失败({exc}),{backoff:.0f}s 后重试一次" - ) - if not self._sleep_interruptible(backoff): - self._mark_task(db, task, "stopped", "任务已停止", result) + if action == "pre_exchange": + try: + check = client.pre_exchange_check( + manual_id=manual_id, commodity_id=commodity_id + ) + user_status = int((check.get("data") or {}).get("userStatus") or 0) + if user_status == 1 and not plan["pre_exchange"]: + active_task = db.get(DouyuTask, task_id) or task + self._mark_task( + db, + active_task, + "success", + f"已预兑: {name},等待开放后继续兑换", + { + "commodity_id": commodity_id, + "plan": plan, + "detail": detail, + "check": check, + }, + ) + return + confirm = client.confirm_pre_exchange( + manual_id=manual_id, commodity_id=commodity_id, rid=rid + ) + except DouyuActivityError as exc: + finish_failed(f"预兑失败: {exc}") + return + active_task = db.get(DouyuTask, task_id) or task + active_account = db.get(Account, account_id) or account + active_account.updated_at = datetime.now(UTC) + self._mark_task( + db, + active_task, + "success", + f"预兑成功: {name},开放后可继续兑换", + { + "commodity_id": commodity_id, + "plan": plan, + "detail": detail, + "check": check, + "confirm": confirm, + }, + ) + return + + # ---- 经典链路:锁单 -> 人类节奏等待 -> 支付(错误分类退避重试)---- + try: + num = max(1, int(payload.get("num") or 1)) + except (TypeError, ValueError): + num = 1 + num = min(num, int(plan.get("max_num") or 1)) + + # 少量随机抖动(浏览器点击商品到锁单之间有人工间隔) + self._push_log("info", f" 兑换 {name}: {plan['text']}") + if not self._sleep_interruptible( + random.uniform(*DOUYU_EXCHANGE_PRE_CREATE_JITTER) + ): + active_task = db.get(DouyuTask, task_id) or task + self._mark_task(db, active_task, "stopped", "任务已停止", result) return try: locked = client.create_exchange_order( @@ -532,103 +528,132 @@ class GoodsMixin: commodity_id=commodity_id, num=num, ) - except DouyuActivityError as exc2: - finish_failed(f"锁定兑换商品失败: {exc2}") + except DouyuActivityError as exc: + # 锁单本身被频控时做一次长退避重试,避免无脑连打 + backoff = ( + DOUYU_EXCHANGE_RATE_LIMIT_BACKOFFS[0] + if self._is_rate_limited_error(str(exc)) + else 3 + ) + self._push_log( + "info", f" 锁定兑换商品失败({exc}),{backoff:.0f}s 后重试一次" + ) + if not self._sleep_interruptible(backoff): + active_task = db.get(DouyuTask, task_id) or task + self._mark_task(db, active_task, "stopped", "任务已停止", result) + return + try: + locked = client.create_exchange_order( + manual_id=manual_id, + rid=rid, + commodity_id=commodity_id, + num=num, + ) + except DouyuActivityError as exc2: + finish_failed(f"锁定兑换商品失败: {exc2}") + return + result.update( + {**locked, "lock_order": locked, "goods": goods_raw} + ) + + # 锁单成功后按浏览器节奏(抓包实测 2.24s~4.2s)等待再支付 + delay = random.uniform(*DOUYU_EXCHANGE_LOCK_PAY_DELAY_RANGE) + self._push_log( + "info", f" 锁单成功(订单 {locked['order_id']}),{delay:.1f}s 后支付" + ) + if not self._sleep_interruptible(delay): + active_task = db.get(DouyuTask, task_id) or task + self._mark_task( + db, active_task, "stopped", "任务已停止,商品锁单仍可能有效", locked + ) + return + try: + payment = self._pay_exchange_with_backoff( + client, + manual_id=manual_id, + order_id=locked["order_id"], + rid=rid, + locked_at=locked["locked_at"], + ) + except DouyuActivityError as exc: + finish_failed(str(exc)) + return + if payment is None: + active_task = db.get(DouyuTask, task_id) or task + self._mark_task( + db, active_task, "stopped", "任务已停止,商品锁单仍可能有效", locked + ) return - result.update( - {**locked, "lock_order": locked, "goods": goods.raw if goods else None} - ) - # 锁单成功后按浏览器节奏(抓包实测 2.24s~4.2s)等待再支付 - delay = random.uniform(*DOUYU_EXCHANGE_LOCK_PAY_DELAY_RANGE) - self._push_log( - "info", f" 锁单成功(订单 {locked['order_id']}),{delay:.1f}s 后支付" - ) - if not self._sleep_interruptible(delay): - self._mark_task( - db, task, "stopped", "任务已停止,商品锁单仍可能有效", locked + result.update( + { + "order_id": locked["order_id"], + "exchange_id": payment["exchange_id"], + "commodity_image": payment["commodity_image"] + or locked["commodity_image"], + "exchange_num": payment["exchange_num"], + "payment": payment, + } ) - return - try: - payment = self._pay_exchange_with_backoff( + active_task = db.get(DouyuTask, task_id) or task + active_account = db.get(Account, account_id) or account + active_account.updated_at = datetime.now(UTC) + # 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功) + points_refresh = None + try: + ctn = query_csrf(client) + points_refresh = self._refresh_account_points( + client, active_account, cookie, ctn=ctn + ) + except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 + self._push_log("warning", f"兑换后刷新积分失败: {exc}") + # ⚠️ **只有这一条 success 是真的兑换**。同一个 handler 里还有三条 + # 「预约到货 / 已预兑 / 预兑确认」的 success —— 它们不消耗积分、也没换到东西, + # 所以**不发事件**。旧收集器只按 status=="success" 收集,导致每预约一次 + # 就生成一条金额为空的 exchange,把 accounts 的 exchange_count 灌大。 + lock_account_row(db, account_id) + record_exchange( + db, + active_account, + task_id=active_task.id, + name=name, + score=locked.get("score"), + commodity_id=commodity_id, + order_id=str(locked.get("order_id") or ""), + exchange_id=str(payment.get("exchange_id") or ""), + game_name=active_account.game_name or "", + game_channel=active_account.game_channel or "", + points_after=(points_refresh or {}).get("points"), + scope="elite", + actor_id=created_by, + ) + self._refresh_high_value_after_exchange( client, + active_account, manual_id=manual_id, - order_id=locked["order_id"], rid=rid, - locked_at=locked["locked_at"], + commodity_name=name, ) - except DouyuActivityError as exc: - finish_failed(str(exc)) - return - if payment is None: self._mark_task( - db, task, "stopped", "任务已停止,商品锁单仍可能有效", locked + db, + active_task, + "success", + f"兑换成功: {name}", + { + "goods": goods_raw, + "game_name": active_account.game_name or "", + "game_channel": active_account.game_channel or "", + "account_name": active_account.nickname + or active_account.username + or active_account.uid + or f"#{active_account.id}", + **result, + **(points_refresh or {}), + }, ) - return - - result.update( - { - "order_id": locked["order_id"], - "exchange_id": payment["exchange_id"], - "commodity_image": payment["commodity_image"] - or locked["commodity_image"], - "exchange_num": payment["exchange_num"], - "payment": payment, - } - ) - account.updated_at = datetime.now(UTC) - # 兑换成功后自动刷新积分,更新账号最新积分信息(失败不阻断兑换成功) - points_refresh = None - try: - ctn = query_csrf(client) - points_refresh = self._refresh_account_points( - client, account, cookie, ctn=ctn - ) - except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 - self._push_log("warning", f"兑换后刷新积分失败: {exc}") - # ⚠️ **只有这一条 success 是真的兑换**。同一个 handler 里还有三条 - # 「预约到货 / 已预兑 / 预兑确认」的 success —— 它们不消耗积分、也没换到东西, - # 所以**不发事件**。旧收集器只按 status=="success" 收集,导致每预约一次 - # 就生成一条金额为空的 exchange,把 accounts 的 exchange_count 灌大。 - record_exchange( - db, - account, - task_id=task.id, - name=name, - score=locked.get("score"), - commodity_id=commodity_id, - order_id=str(locked.get("order_id") or ""), - exchange_id=str(payment.get("exchange_id") or ""), - game_name=account.game_name or "", - game_channel=account.game_channel or "", - points_after=(points_refresh or {}).get("points"), - scope="elite", - actor_id=int(task.created_by), - ) - self._refresh_high_value_after_exchange( - client, - account, - manual_id=manual_id, - rid=rid, - commodity_name=name, - ) - self._mark_task( - db, - task, - "success", - f"兑换成功: {name}", - { - "goods": goods.raw if goods else None, - "game_name": account.game_name or "", - "game_channel": account.game_channel or "", - "account_name": account.nickname - or account.username - or account.uid - or f"#{account.id}", - **result, - **(points_refresh or {}), - }, - ) + finally: + if isinstance(client, DouyuActivityClient): + client.close() def _execute_exchange_esports_goods( self, @@ -713,6 +738,8 @@ class GoodsMixin: and isinstance(after_points, (int, float)) else None ) + if account.id is not None: + lock_account_row(db, int(account.id)) record_exchange( db, account, diff --git a/web/backend/services/douyu_runner_xpd.py b/web/backend/services/douyu_runner_xpd.py index d7c84c5..261a9fc 100644 --- a/web/backend/services/douyu_runner_xpd.py +++ b/web/backend/services/douyu_runner_xpd.py @@ -18,6 +18,7 @@ from .account_binding import ( SCOPE_PEACE, set_bind_status, ) +from .account_sync_service import lock_account_row from .business_events import record_exchange from .douyu_activity_query import ( query_xpd_bind_info, @@ -597,6 +598,8 @@ class XpdMixin: # 和平小店兑换 —— 此前从不发事件(不在旧收集器的 allowlist 里)。 # 消耗的是点券或扭蛋碎片,不是积分;金额用本地已知的 price(快照标价, # 已在上面校验过 > 0),作用域标成 peace 以便和精英/电竞区分。 + if account.id is not None: + lock_account_row(db, int(account.id)) record_exchange( db, account, diff --git a/web/backend/services/execution_jobs.py b/web/backend/services/execution_jobs.py index f1c07cb..7b750c6 100644 --- a/web/backend/services/execution_jobs.py +++ b/web/backend/services/execution_jobs.py @@ -384,6 +384,7 @@ class ExecutionEventBatchWriter: self._flushing = False self._stop = False self._thread: threading.Thread | None = None + self._failed_batches = 0 def start(self) -> None: with self._cond: @@ -401,6 +402,15 @@ class ExecutionEventBatchWriter: with self._cond: return self._thread is not None and self._thread.is_alive() + def status(self) -> dict[str, Any]: + with self._cond: + return { + "running": self._thread is not None and self._thread.is_alive(), + "pending": len(self._queue), + "flushing": self._flushing, + "failed_batches": self._failed_batches, + } + def _drain_sync(self) -> bool: """在后台线程未运行时按 FIFO 同步写完队列中剩余事件。""" with self._write_lock: @@ -486,7 +496,10 @@ class ExecutionEventBatchWriter: self._flushing = True try: with self._write_lock: - append_execution_events(batch) + ok = append_execution_events(batch) + if not ok: + with self._cond: + self._failed_batches += 1 finally: with self._cond: self._flushing = False diff --git a/web/backend/services/execution_worker.py b/web/backend/services/execution_worker.py index 265ef7e..1ddf0e1 100644 --- a/web/backend/services/execution_worker.py +++ b/web/backend/services/execution_worker.py @@ -100,6 +100,10 @@ class ExecutionJobWorker: self._inflight: dict[str, int] = {} self._owner = execution_worker_owner() self._event_writer = ExecutionEventBatchWriter() + self._last_poll_at: str | None = None + self._last_claim_error: str | None = None + self._last_claim_error_at: str | None = None + self._total_claimed = 0 def start(self) -> bool: with self._lock: @@ -159,23 +163,27 @@ class ExecutionJobWorker: DEFAULT_POLL_SECONDS, ) while not self._stop.is_set(): - # 回收已完成的 job,同时把 lane 的在途计数减回来。 - for future in [item for item in futures if item.done()]: - lane = futures.pop(future) - self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1) - try: - future.result() - except Exception: # noqa: BLE001, S110 - 结果已落库,这里只消费异常 - pass - executors = self._executors - if not executors: - break - slots = max_jobs - sum(self._inflight.values()) + now_iso = datetime.now(UTC).isoformat() + with self._lock: + self._last_poll_at = now_iso + # 回收已完成的 job,同时把 lane 的在途计数减回来。 + for future in [item for item in futures if item.done()]: + lane = futures.pop(future) + self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1) + try: + future.result() + except Exception: # noqa: BLE001, S110 - 结果已落库,这里只消费异常 + pass + executors = dict(self._executors) + if not executors: + break + slots = max_jobs - sum(self._inflight.values()) + inflight_snapshot = dict(self._inflight) if slots > 0: # 履约优先:先把 fulfillment 的槽填满,登录只用剩下的。 # 登录批次等邮箱验证码时可能持槽 25 分钟,绝不能把履约饿死。 for lane in _lane_claim_order(): - lane_free = lane_limits.get(lane, 0) - self._inflight.get(lane, 0) + lane_free = lane_limits.get(lane, 0) - inflight_snapshot.get(lane, 0) take = min(slots, lane_free) if take <= 0: continue @@ -185,7 +193,12 @@ class ExecutionJobWorker: owner=self._owner, limit=take, ) - except Exception: # noqa: BLE001 - 消费循环必须存活 + with self._lock: + self._last_claim_error = None + except Exception as exc: # noqa: BLE001 - 消费循环必须存活 + with self._lock: + self._last_claim_error = f"{type(exc).__name__}: {exc}"[:500] + self._last_claim_error_at = now_iso logger.exception("领取执行任务失败 lane={}", lane) jobs = [] executor = executors.get(lane) @@ -196,7 +209,10 @@ class ExecutionJobWorker: future = executor.submit(self._run_job, job.id) except RuntimeError: break - self._inflight[lane] = self._inflight.get(lane, 0) + 1 + with self._lock: + self._inflight[lane] = self._inflight.get(lane, 0) + 1 + self._total_claimed += 1 + inflight_snapshot[lane] = inflight_snapshot.get(lane, 0) + 1 futures[future] = lane slots -= len(jobs) if futures: @@ -384,16 +400,30 @@ def stop_execution_job_worker() -> None: def execution_job_worker_status() -> dict[str, Any]: - thread = execution_job_worker._thread + with execution_job_worker._lock: + thread = execution_job_worker._thread + inflight = dict(execution_job_worker._inflight) + last_poll_at = execution_job_worker._last_poll_at + last_claim_error = execution_job_worker._last_claim_error + last_claim_error_at = execution_job_worker._last_claim_error_at + total_claimed = execution_job_worker._total_claimed + event_writer = execution_job_worker._event_writer.status() return { "running": bool(thread and thread.is_alive()), "lanes": list(_lane_scopes()), "lane_slots": _lane_slot_limits(), + "inflight": inflight, + "inflight_total": sum(inflight.values()), "max_jobs": _env_positive_int( "EXECUTION_WORKER_MAX_JOBS", DEFAULT_EXECUTION_WORKERS, ), "owner": execution_job_worker._owner, + "total_claimed": total_claimed, + "last_poll_at": last_poll_at, + "last_claim_error": last_claim_error, + "last_claim_error_at": last_claim_error_at, + "event_writer": event_writer, } diff --git a/web/backend/services/login_service.py b/web/backend/services/login_service.py index 4166ea1..bb61f76 100644 --- a/web/backend/services/login_service.py +++ b/web/backend/services/login_service.py @@ -836,9 +836,16 @@ class LoginBatchRunner: stop_event=self._stop, api_strategy=self.api_strategy, ) - result = ( - loginer.check_account() if self.mode == "check" else loginer.login() - ) + try: + result = ( + loginer.check_account() + if self.mode == "check" + else loginer.login() + ) + finally: + close = getattr(loginer, "close", None) + if callable(close): + close() if self.mode == "check" and result.success: status = ( diff --git a/web/backend/services/payment_poll_scheduler.py b/web/backend/services/payment_poll_scheduler.py index 11621c1..8c77b81 100644 --- a/web/backend/services/payment_poll_scheduler.py +++ b/web/backend/services/payment_poll_scheduler.py @@ -32,6 +32,17 @@ _thread: threading.Thread | None = None _lock = threading.Lock() _in_flight: set[int] = set() _in_flight_lock = threading.Lock() +_metrics_lock = threading.Lock() +_metrics: dict[str, object] = { + "last_tick_at": None, + "last_dispatched_at": None, + "last_claimed": 0, + "last_submitted": 0, + "total_dispatched": 0, + "consecutive_errors": 0, + "last_error": None, + "last_error_at": None, +} def _env_int(name: str, default: int, minimum: int, maximum: int) -> int: @@ -184,6 +195,9 @@ def _release_callback(future: Future) -> None: def run_payment_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int: capacity = available_slots(TaskLane.PAYMENT_POLL) if capacity <= 0: + with _metrics_lock: + _metrics["last_claimed"] = 0 + _metrics["last_submitted"] = 0 return 0 claimed = _claim_due_payment_tasks(min(max(1, limit), capacity)) submitted = 0 @@ -200,6 +214,12 @@ def run_payment_poll_dispatch_once(limit: int = DEFAULT_BATCH_SIZE) -> int: break future.add_done_callback(_release_callback) submitted += 1 + with _metrics_lock: + _metrics["last_claimed"] = len(claimed) + _metrics["last_submitted"] = submitted + if submitted: + _metrics["total_dispatched"] = int(_metrics["total_dispatched"] or 0) + submitted + _metrics["last_dispatched_at"] = datetime.now(UTC).isoformat() return submitted @@ -211,6 +231,9 @@ def _run() -> None: 30, ) while not _stop_event.is_set(): + now_iso = datetime.now(UTC).isoformat() + with _metrics_lock: + _metrics["last_tick_at"] = now_iso try: batch_size = _env_int( "PAYMENT_POLL_DISPATCH_BATCH", @@ -219,7 +242,15 @@ def _run() -> None: 200, ) run_payment_poll_dispatch_once(batch_size) + with _metrics_lock: + _metrics["consecutive_errors"] = 0 except Exception as exc: # noqa: BLE001 - scheduler survives any one bad tick + with _metrics_lock: + _metrics["consecutive_errors"] = ( + int(_metrics["consecutive_errors"] or 0) + 1 + ) + _metrics["last_error"] = f"{type(exc).__name__}: {exc}"[:500] + _metrics["last_error_at"] = now_iso logger.warning("支付到账调度轮次失败: {}", exc) _stop_event.wait(interval) @@ -255,10 +286,13 @@ def scheduler_status() -> dict[str, object]: running = _thread is not None and _thread.is_alive() with _in_flight_lock: in_flight = len(_in_flight) + with _metrics_lock: + metrics = dict(_metrics) return { "running": running, "in_flight": in_flight, "claim_seconds": CLAIM_SECONDS, + **metrics, } diff --git a/web/backend/services/platform_fulfillment/allocation.py b/web/backend/services/platform_fulfillment/allocation.py index a8a3d7a..3627d02 100644 --- a/web/backend/services/platform_fulfillment/allocation.py +++ b/web/backend/services/platform_fulfillment/allocation.py @@ -527,8 +527,7 @@ def _find_reusable_same_role_target( PlatformFulfillmentTask.id != int(task.id), PlatformFulfillmentTask.account_id.isnot(None), PlatformFulfillmentTask.execution_status != "cancelled", - func.lower(func.trim(PlatformFulfillmentTask.customer_role_name)) - == role.casefold(), + PlatformFulfillmentTask.customer_role_norm == role.strip().casefold(), ) .order_by( case((PlatformFulfillmentTask.lease_id.isnot(None), 0), else_=1), diff --git a/web/backend/services/platform_fulfillment/binding.py b/web/backend/services/platform_fulfillment/binding.py index 934b726..bf62ef2 100644 --- a/web/backend/services/platform_fulfillment/binding.py +++ b/web/backend/services/platform_fulfillment/binding.py @@ -7,7 +7,7 @@ from datetime import timedelta from typing import Any from fastapi import HTTPException -from sqlalchemy import case, func +from sqlalchemy import case from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from starlette.concurrency import run_in_threadpool @@ -249,8 +249,8 @@ def _propagate_same_role_binding_to_siblings( PlatformFulfillmentTask.execution_status.notin_(("completed", "cancelled")), PlatformFulfillmentTask.binding_status.in_(ACTIVE_BINDING_STATUSES), PlatformFulfillmentTask.customer_role_name != "", - func.lower(func.trim(PlatformFulfillmentTask.customer_role_name)) - == role_name.casefold(), + PlatformFulfillmentTask.customer_role_norm + == role_name.strip().casefold(), ) .order_by(PlatformFulfillmentTask.id.asc()) .with_for_update(skip_locked=True) @@ -2286,6 +2286,10 @@ def verify_task_binding_sync( role = resolve_elite_role(client, config) except Exception as exc: # noqa: BLE001 role = {"status": ROLE_ERROR, "errors": [str(exc)], "bind_infos": []} + finally: + close = getattr(client, "close", None) + if callable(close): + close() bind_infos = [ item for item in (role.get("bind_infos") or []) if isinstance(item, dict) diff --git a/web/backend/services/task_runtime.py b/web/backend/services/task_runtime.py index 6af4fe7..eedaf82 100644 --- a/web/backend/services/task_runtime.py +++ b/web/backend/services/task_runtime.py @@ -12,7 +12,7 @@ import os import threading from collections.abc import Callable from concurrent.futures import Future, ThreadPoolExecutor -from dataclasses import dataclass +from dataclasses import dataclass, field from enum import StrEnum from typing import Any @@ -97,6 +97,12 @@ class _LaneRuntime: config: LaneConfig executor: ThreadPoolExecutor admission: threading.BoundedSemaphore + lock: threading.Lock = field(default_factory=threading.Lock) + in_flight: int = 0 + active: int = 0 + waiting: int = 0 + submitted: int = 0 + rejected: int = 0 _LOCK = threading.RLock() @@ -134,21 +140,44 @@ def _submit[T]( if stopped is not None and stopped(): return None if wait: - while True: - if stopped is not None and stopped(): - return None - if runtime.admission.acquire(timeout=0.2): - break + with runtime.lock: + runtime.waiting += 1 + try: + while True: + if stopped is not None and stopped(): + return None + if runtime.admission.acquire(timeout=0.2): + break + finally: + with runtime.lock: + runtime.waiting = max(0, runtime.waiting - 1) elif not runtime.admission.acquire(blocking=False): + with runtime.lock: + runtime.rejected += 1 return None + with runtime.lock: + runtime.in_flight += 1 + runtime.submitted += 1 + def run() -> T: + with runtime.lock: + runtime.active += 1 try: return fn(*args, **kwargs) finally: + with runtime.lock: + runtime.active = max(0, runtime.active - 1) + runtime.in_flight = max(0, runtime.in_flight - 1) runtime.admission.release() - return runtime.executor.submit(run) + try: + return runtime.executor.submit(run) + except Exception: + with runtime.lock: + runtime.in_flight = max(0, runtime.in_flight - 1) + runtime.admission.release() + raise def submit[T]( @@ -196,7 +225,8 @@ def try_submit[T]( def available_slots(lane: TaskLane) -> int: """Return the number of tasks that can currently enter a lane immediately.""" runtime = _runtime(lane) - return max(0, int(runtime.admission._value)) + with runtime.lock: + return max(0, runtime.config.max_in_flight - runtime.in_flight) def lane_stats() -> dict[str, dict[str, int]]: @@ -204,10 +234,23 @@ def lane_stats() -> dict[str, dict[str, int]]: runtimes = list(_RUNTIMES.items()) stats: dict[str, dict[str, int]] = {} for lane, runtime in runtimes: + with runtime.lock: + in_flight = runtime.in_flight + active = runtime.active + waiting = runtime.waiting + submitted = runtime.submitted + rejected = runtime.rejected + available = max(0, runtime.config.max_in_flight - in_flight) stats[lane.value] = { "workers": runtime.config.workers, "max_in_flight": runtime.config.max_in_flight, - "admission_value": runtime.admission._value, + "admission_value": available, + "in_flight": in_flight, + "active": active, + "queued": max(0, in_flight - active), + "waiting": waiting, + "submitted": submitted, + "rejected": rejected, } return stats