fix(douyu): 修复斗鱼链路 P0/P1 隐患并增强 P2 运维队列可观测性

This commit is contained in:
yml
2026-11-29 14:10:24 +08:00
parent be7146a9ef
commit d12d9e02b3
51 changed files with 2510 additions and 561 deletions
+15 -1
View File
@@ -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()
+35 -6
View File
@@ -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 邮件列表(含精确日期) ────────────────────
+35 -16
View File
@@ -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: 提交验证码...")
+39 -35
View File
@@ -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
+15 -12
View File
@@ -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:
+15 -12
View File
@@ -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:
+5 -3
View File
@@ -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)
+27 -20
View File
@@ -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)} 个代理均不可用"
+15 -1
View File
@@ -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()