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
+101 -22
View File
@@ -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()