fix: 代理分配看延迟,采集失败不再丢掉其余类型
This commit is contained in:
+58
-15
@@ -15,6 +15,7 @@ log = logging.getLogger(__name__)
|
||||
|
||||
CHINA = {"cn", "chn", "china", "中国"}
|
||||
_SOURCE_TITLES = {"proxyhub": "ProxyHub"}
|
||||
MAX_RESPONSE_BYTES = 1_048_576
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -163,19 +164,57 @@ def parse_proxyhub_result(payload: object) -> list[ProxyCandidate]:
|
||||
return []
|
||||
|
||||
|
||||
def _read_mcp(response: httpx.Response) -> dict:
|
||||
ctype = (response.headers.get("content-type") or "").lower()
|
||||
if "json" in ctype:
|
||||
payload = response.json()
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
for line in response.text.splitlines():
|
||||
if line.startswith("data:"):
|
||||
payload = json.loads(line[5:].strip() or "{}")
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
payload = json.loads(response.text or "{}")
|
||||
def _json_dict(text: str) -> dict:
|
||||
try:
|
||||
payload = json.loads(text or "{}")
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
|
||||
|
||||
def _limited_body(response: httpx.Response) -> bytes:
|
||||
declared = response.headers.get("content-length")
|
||||
if declared and declared.isdigit() and int(declared) > MAX_RESPONSE_BYTES:
|
||||
raise ValueError("上游响应过大")
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
for chunk in response.iter_bytes():
|
||||
total += len(chunk)
|
||||
if total > MAX_RESPONSE_BYTES:
|
||||
raise ValueError("上游响应过大")
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def _read_mcp(response: httpx.Response) -> dict:
|
||||
text = _limited_body(response).decode("utf-8", errors="replace")
|
||||
ctype = (response.headers.get("content-type") or "").lower()
|
||||
if "json" in ctype and "event-stream" not in ctype:
|
||||
parsed = _json_dict(text)
|
||||
if parsed or text.strip() in {"", "{}"}:
|
||||
return parsed
|
||||
chosen: dict | None = None
|
||||
saw_data = False
|
||||
for line in text.splitlines():
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
saw_data = True
|
||||
raw = line[5:].strip()
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if not isinstance(payload, dict):
|
||||
continue
|
||||
if chosen is None or "result" in payload or "error" in payload:
|
||||
chosen = payload
|
||||
if saw_data:
|
||||
return chosen or {}
|
||||
return _json_dict(text)
|
||||
|
||||
|
||||
class ProxyHubCollector(Collector):
|
||||
name = "proxyhub"
|
||||
url = "https://proxyhub.me/api/mcp"
|
||||
@@ -185,9 +224,13 @@ class ProxyHubCollector(Collector):
|
||||
def collect(self) -> list[ProxyCandidate]:
|
||||
items: list[ProxyCandidate] = []
|
||||
with ThreadPoolExecutor(max_workers=len(self.types)) as pool:
|
||||
futures = [pool.submit(self._list, kind) for kind in self.types]
|
||||
futures = {pool.submit(self._list, kind): kind for kind in self.types}
|
||||
for future in as_completed(futures):
|
||||
items.extend(future.result())
|
||||
kind = futures[future]
|
||||
try:
|
||||
items.extend(future.result())
|
||||
except Exception:
|
||||
log.warning("上游 %s 的 %s 没有获取到", self.name, kind, exc_info=True)
|
||||
return items
|
||||
|
||||
def _list(self, kind: str) -> list[ProxyCandidate]:
|
||||
@@ -213,9 +256,9 @@ class ProxyHubCollector(Collector):
|
||||
"Mcp-Name": "list_proxies",
|
||||
}
|
||||
with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client:
|
||||
response = client.post(self.url, headers=headers, json=body)
|
||||
response.raise_for_status()
|
||||
return parse_proxyhub_result(_read_mcp(response))
|
||||
with client.stream("POST", self.url, headers=headers, json=body) as response:
|
||||
response.raise_for_status()
|
||||
return parse_proxyhub_result(_read_mcp(response))
|
||||
|
||||
|
||||
register(ProxyHubCollector())
|
||||
|
||||
Reference in New Issue
Block a user