fix: 代理分配看延迟,采集失败不再丢掉其余类型

This commit is contained in:
2026-11-16 12:02:10 +08:00
parent 8504ff5e85
commit 05f2396e35
3 changed files with 252 additions and 83 deletions
+58 -15
View File
@@ -15,6 +15,7 @@ log = logging.getLogger(__name__)
CHINA = {"cn", "chn", "china", "中国"} CHINA = {"cn", "chn", "china", "中国"}
_SOURCE_TITLES = {"proxyhub": "ProxyHub"} _SOURCE_TITLES = {"proxyhub": "ProxyHub"}
MAX_RESPONSE_BYTES = 1_048_576
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -163,19 +164,57 @@ def parse_proxyhub_result(payload: object) -> list[ProxyCandidate]:
return [] return []
def _read_mcp(response: httpx.Response) -> dict: def _json_dict(text: str) -> dict:
ctype = (response.headers.get("content-type") or "").lower() try:
if "json" in ctype: payload = json.loads(text or "{}")
payload = response.json() except json.JSONDecodeError:
return payload if isinstance(payload, dict) else {} return {}
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 "{}")
return payload if isinstance(payload, dict) else {} 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): class ProxyHubCollector(Collector):
name = "proxyhub" name = "proxyhub"
url = "https://proxyhub.me/api/mcp" url = "https://proxyhub.me/api/mcp"
@@ -185,9 +224,13 @@ class ProxyHubCollector(Collector):
def collect(self) -> list[ProxyCandidate]: def collect(self) -> list[ProxyCandidate]:
items: list[ProxyCandidate] = [] items: list[ProxyCandidate] = []
with ThreadPoolExecutor(max_workers=len(self.types)) as pool: 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): 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 return items
def _list(self, kind: str) -> list[ProxyCandidate]: def _list(self, kind: str) -> list[ProxyCandidate]:
@@ -213,9 +256,9 @@ class ProxyHubCollector(Collector):
"Mcp-Name": "list_proxies", "Mcp-Name": "list_proxies",
} }
with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client: with httpx.Client(timeout=20, follow_redirects=True, trust_env=False) as client:
response = client.post(self.url, headers=headers, json=body) with client.stream("POST", self.url, headers=headers, json=body) as response:
response.raise_for_status() response.raise_for_status()
return parse_proxyhub_result(_read_mcp(response)) return parse_proxyhub_result(_read_mcp(response))
register(ProxyHubCollector()) register(ProxyHubCollector())
+58 -15
View File
@@ -26,15 +26,42 @@ def canonical_scheme(scheme: str | None) -> str:
return kind return kind
def _unwrap_host(host: str) -> str:
text = host.strip()
if len(text) >= 2 and text.startswith("[") and text.endswith("]"):
return text[1:-1]
return text
def _host_is_public(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
return not (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_reserved
or ip.is_multicast
or ip.is_unspecified
)
def _reject_private(addresses: list[ipaddress.IPv4Address | ipaddress.IPv6Address]) -> None:
for ip in addresses:
if not _host_is_public(ip):
raise ProxyError("代理只允许公网地址")
def assert_public_host(host: str) -> None: def assert_public_host(host: str) -> None:
"""手填和采集都只接受公网地址。""" """手填和采集都只接受公网地址。"""
address = (host or "").strip() address = (host or "").strip()
if not address or any(char in address for char in "@/#?"): if not address or any(char in address for char in "@/#?"):
raise ProxyError("代理只允许公网地址") raise ProxyError("代理只允许公网地址")
bare = _unwrap_host(address)
if bare != address and (not bare or any(char in bare for char in "[]/@#?")):
raise ProxyError("代理地址不合法")
try: try:
addresses = [ipaddress.ip_address(address)] addresses = [ipaddress.ip_address(bare)]
except ValueError: except ValueError:
if not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"): if bare != address or not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"):
raise ProxyError("代理地址不合法") raise ProxyError("代理地址不合法")
try: try:
found = socket.getaddrinfo(address, None) found = socket.getaddrinfo(address, None)
@@ -48,24 +75,35 @@ def assert_public_host(host: str) -> None:
continue continue
if not addresses: if not addresses:
raise ProxyError("代理地址无法解析") raise ProxyError("代理地址无法解析")
for ip in addresses: _reject_private(addresses)
if (
ip.is_private
or ip.is_loopback
or ip.is_link_local
or ip.is_reserved
or ip.is_multicast
or ip.is_unspecified
):
raise ProxyError("代理只允许公网地址")
def _host_for_url(host: str) -> str: def _host_for_url(host: str) -> str:
bare = _unwrap_host(host)
try: try:
ipaddress.IPv6Address(host) ipaddress.IPv6Address(bare)
except ValueError: except ValueError:
return host return host.strip() or host
return f"[{host}]" return f"[{bare}]"
def _written_host(host: str) -> str:
"""主机名只留字母、数字、点和横线;IPv6 写入时加方括号。"""
address = host.strip()
if not address or any(char in address for char in "@/#?"):
raise ProxyError("代理地址不合法")
bare = _unwrap_host(address)
if bare != address and (not bare or any(char in bare for char in "[]")):
raise ProxyError("代理地址不合法")
try:
parsed = ipaddress.ip_address(bare)
except ValueError:
if bare != address or not re.fullmatch(r"[A-Za-z0-9.-]+", address) or ".." in address or address.startswith("-"):
raise ProxyError("代理地址不合法")
return address
if isinstance(parsed, ipaddress.IPv6Address):
return f"[{bare}]"
return bare
def parse_proxy(value: str | None) -> str | None: def parse_proxy(value: str | None) -> str | None:
@@ -79,6 +117,8 @@ def parse_proxy(value: str | None) -> str | None:
scheme = canonical_scheme(parsed.scheme) scheme = canonical_scheme(parsed.scheme)
if scheme not in SCHEMES: if scheme not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5") raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
if parsed.path not in ("", "/") or parsed.query or parsed.fragment:
raise ProxyError("代理地址不合法")
if not parsed.hostname: if not parsed.hostname:
raise ProxyError("代理地址不完整") raise ProxyError("代理地址不完整")
host = _host_for_url(parsed.hostname) host = _host_for_url(parsed.hostname)
@@ -115,6 +155,9 @@ def validate_parts(scheme: str, host: str, port: object, username: str = "") ->
address = (host or "").strip() address = (host or "").strip()
if not address or "://" in address or any(ch.isspace() for ch in address): if not address or "://" in address or any(ch.isspace() for ch in address):
raise ProxyError("请填写代理地址") raise ProxyError("请填写代理地址")
if len(address) > 255:
raise ProxyError("代理地址过长")
address = _written_host(address)
if len(address) > 255: if len(address) > 255:
raise ProxyError("代理地址过长") raise ProxyError("代理地址过长")
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535: if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
+136 -53
View File
@@ -11,6 +11,7 @@ from urllib.parse import urlparse
import httpx import httpx
from sqlalchemy import case, func, select from sqlalchemy import case, func, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API
@@ -30,6 +31,7 @@ LATENCY_LIMIT = 3.0
LATENCY_LIMIT_MS = 3000 LATENCY_LIMIT_MS = 3000
PROBE_CONCURRENCY = 16 PROBE_CONCURRENCY = 16
MAX_PROBES = 80 MAX_PROBES = 80
ALIVE_REPROBE_SLOTS = 20
MAX_SWITCHES = 8 MAX_SWITCHES = 8
PROBE_URL = EUNIV + "/" PROBE_URL = EUNIV + "/"
PROBE_URLS = ( PROBE_URLS = (
@@ -62,10 +64,20 @@ def _url(node: ProxyNode) -> str:
def _sync_row(db: Session) -> ProxyPoolSync: def _sync_row(db: Session) -> ProxyPoolSync:
row = db.get(ProxyPoolSync, 1) row = db.get(ProxyPoolSync, 1)
if row is None: if row is not None:
row = ProxyPoolSync(id=1) return row
db.add(row) row = ProxyPoolSync(id=1)
db.flush() try:
with db.begin_nested():
db.add(row)
db.flush()
except IntegrityError:
if row in db:
db.expunge(row)
found = db.get(ProxyPoolSync, 1)
if found is None:
raise
return found
return row return row
@@ -193,8 +205,6 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
reasons.append(_short_reason(exc)) reasons.append(_short_reason(exc))
except Exception as exc: except Exception as exc:
return False, 0, _short_reason(exc) return False, 0, _short_reason(exc)
if not samples:
return False, 0, reasons[0] if reasons else "无法连接"
average = int(round(sum(samples) / len(samples))) average = int(round(sum(samples) / len(samples)))
if reasons: if reasons:
return False, average, reasons[0] return False, average, reasons[0]
@@ -218,15 +228,28 @@ def _direct_reaches_target() -> bool:
return False return False
def _clip_reason(reason: str, fallback: str = "失效") -> str:
text = (reason or "").strip() or fallback
if len(text) <= 200:
return text
log.warning("代理失败原因:%s", text)
return text[:200]
def _short_reason(exc: BaseException) -> str: def _short_reason(exc: BaseException) -> str:
from python_socks import ProxyConnectionError, ProxyTimeoutError from python_socks import ProxyConnectionError, ProxyTimeoutError
if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException, ProxyTimeoutError)):
return "超时"
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError, ProxyConnectionError)):
return "无法连接"
text = str(exc).strip() or type(exc).__name__ text = str(exc).strip() or type(exc).__name__
return text[:200] if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException, ProxyTimeoutError)):
stored = "超时"
elif isinstance(exc, (httpx.ProxyError, httpx.ConnectError, ProxyConnectionError)):
stored = "无法连接"
else:
stored = text
if stored != text:
log.warning("代理失败原因:%s", text)
return stored
return _clip_reason(stored)
def _find_node(db: Session, scheme: str, host: str, port: int) -> ProxyNode | None: def _find_node(db: Session, scheme: str, host: str, port: int) -> ProxyNode | None:
@@ -267,24 +290,47 @@ def acquire(employee_id: str) -> str | None:
if held is not None and held.status == STATUS_ALIVE: if held is not None and held.status == STATUS_ALIVE:
return _url(held) return _url(held)
_holds.pop(key, None) _holds.pop(key, None)
if held is not None:
held.assigns = _occupancy(held.id)
nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all()) nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all())
if not nodes: if not nodes:
db.commit()
return None return None
load = {node.id: 0 for node in nodes} load = {node.id: 0 for node in nodes}
for node_id in _holds.values(): for node_id in _holds.values():
if node_id in load: if node_id in load:
load[node_id] += 1 load[node_id] += 1
nodes.sort(key=lambda node: (load[node.id], node.assigns, node.id)) for node in nodes:
node.assigns = load[node.id]
nodes.sort(key=lambda node: (load[node.id], _latency_rank(node), node.assigns, node.id))
pick = nodes[0] pick = nodes[0]
_holds[key] = pick.id _holds[key] = pick.id
pick.assigns = int(pick.assigns or 0) + 1 pick.assigns = load[pick.id] + 1
db.commit() db.commit()
return _url(pick) return _url(pick)
def _latency_rank(node: ProxyNode) -> int:
if node.latency_ms is None:
return 1_000_000_000
return int(node.latency_ms)
def _occupancy(node_id: int) -> int:
return sum(1 for held in _holds.values() if held == node_id)
def release(employee_id: str) -> None: def release(employee_id: str) -> None:
with _assign_lock: key = (employee_id or "").strip()
_holds.pop((employee_id or "").strip(), None) with SessionLocal() as db, _assign_lock:
node_id = _holds.pop(key, None)
if node_id is None:
return
node = db.get(ProxyNode, node_id)
if node is None:
return
node.assigns = _occupancy(node_id)
db.commit()
def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None: def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None:
@@ -300,8 +346,9 @@ def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = ""
if held == node.id: if held == node.id:
_holds.pop(key, None) _holds.pop(key, None)
node.status = STATUS_DEAD node.status = STATUS_DEAD
node.fail_reason = (reason or "失效")[:200] node.fail_reason = _clip_reason(reason)
node.last_checked_at = _now() node.last_checked_at = _now()
node.assigns = 0
_evict_node(node.id) _evict_node(node.id)
db.commit() db.commit()
@@ -365,8 +412,12 @@ def _refresh_body() -> dict:
elif node.status == STATUS_ALIVE: elif node.status == STATUS_ALIVE:
alive_ids.append(node.id) alive_ids.append(node.id)
for node in existing.values(): for node in existing.values():
if node.status == STATUS_ALIVE and node.id not in alive_ids and node.id not in new_ids: if node.id in alive_ids or node.id in new_ids or node.id in dead_ids:
continue
if node.status == STATUS_ALIVE:
alive_ids.append(node.id) alive_ids.append(node.id)
elif node.status == STATUS_NEW:
new_ids.append(node.id)
db.commit() db.commit()
probe_ids = _pick_probe_ids(db, new_ids, alive_ids, dead_ids) probe_ids = _pick_probe_ids(db, new_ids, alive_ids, dead_ids)
nodes = [db.get(ProxyNode, node_id) for node_id in probe_ids] nodes = [db.get(ProxyNode, node_id) for node_id in probe_ids]
@@ -389,16 +440,7 @@ def _refresh_body() -> dict:
node = db.get(ProxyNode, node_id) node = db.get(ProxyNode, node_id)
if node is None: if node is None:
continue continue
node.last_checked_at = _now() _apply_probe(node, ok, latency, reason)
node.latency_ms = latency
if ok:
node.status = STATUS_ALIVE
node.last_ok_at = node.last_checked_at
node.fail_reason = ""
else:
node.status = STATUS_DEAD
node.fail_reason = reason or "失效"
_evict_node(node.id)
sync.checked_at = _now() sync.checked_at = _now()
sync.running = False sync.running = False
db.flush() db.flush()
@@ -421,42 +463,69 @@ def _refresh_body() -> dict:
return sync_view(db) return sync_view(db)
def _aware(value: datetime | None) -> datetime | None:
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
def _load_nodes(db: Session, ids: list[int]) -> list[ProxyNode]:
nodes: list[ProxyNode] = []
seen: set[int] = set()
for node_id in ids:
if node_id in seen:
continue
seen.add(node_id)
node = db.get(ProxyNode, node_id)
if node is not None:
nodes.append(node)
return nodes
def _unchecked_first(node: ProxyNode) -> tuple:
checked = _aware(node.last_checked_at)
return (checked is not None, checked or datetime.min.replace(tzinfo=timezone.utc), node.id)
def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int], dead_ids: list[int] | None = None) -> list[int]: def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int], dead_ids: list[int] | None = None) -> list[int]:
new_nodes = _load_nodes(db, new_ids)
new_nodes.sort(key=_unchecked_first)
alive_nodes = _load_nodes(db, alive_ids)
alive_nodes.sort(key=_unchecked_first)
reserve = min(ALIVE_REPROBE_SLOTS, len(alive_nodes))
new_budget = MAX_PROBES - reserve
ordered: list[int] = [] ordered: list[int] = []
seen: set[int] = set() seen: set[int] = set()
for node_id in new_ids:
if node_id not in seen: def add(node_id: int) -> None:
seen.add(node_id) if node_id in seen or len(ordered) >= MAX_PROBES:
ordered.append(node_id) return
if len(ordered) >= MAX_PROBES: seen.add(node_id)
return ordered[:MAX_PROBES] ordered.append(node_id)
alive_nodes = [
node for node in new_nodes:
for node in (db.get(ProxyNode, node_id) for node_id in alive_ids) if len(ordered) >= new_budget:
if node is not None break
] add(node.id)
alive_nodes.sort(key=lambda node: (node.last_checked_at is not None, node.last_checked_at or _now(), node.id))
for node in alive_nodes: for node in alive_nodes:
if node.id in seen:
continue
seen.add(node.id)
ordered.append(node.id)
if len(ordered) >= MAX_PROBES: if len(ordered) >= MAX_PROBES:
break break
add(node.id)
for node in new_nodes:
if len(ordered) >= MAX_PROBES:
break
add(node.id)
cutoff = _now() - timedelta(minutes=30) cutoff = _now() - timedelta(minutes=30)
for node_id in dead_ids or []: for node_id in dead_ids or []:
if len(ordered) >= MAX_PROBES or node_id in seen: if len(ordered) >= MAX_PROBES or node_id in seen:
continue continue
node = db.get(ProxyNode, node_id) node = db.get(ProxyNode, node_id)
checked = node.last_checked_at if node is not None else None checked = _aware(node.last_checked_at) if node is not None else None
if checked is None: if checked is None or checked > cutoff:
continue continue
if checked.tzinfo is None: add(node_id)
checked = checked.replace(tzinfo=timezone.utc)
if checked > cutoff:
continue
seen.add(node_id)
ordered.append(node_id)
return ordered return ordered
@@ -489,7 +558,8 @@ def _apply_probe(node: ProxyNode, ok: bool, latency: int, reason: str) -> None:
node.fail_reason = "" node.fail_reason = ""
else: else:
node.status = STATUS_DEAD node.status = STATUS_DEAD
node.fail_reason = (reason or "失效")[:200] node.fail_reason = _clip_reason(reason)
node.assigns = 0
_evict_node(node.id) _evict_node(node.id)
@@ -525,8 +595,10 @@ def request_probe(ids: list[int] | None = None) -> dict:
_probe_state["count"] = int(result.get("count") or 0) _probe_state["count"] = int(result.get("count") or 0)
_probe_state["error"] = "" _probe_state["error"] = ""
except Exception as exc: except Exception as exc:
log.warning("代理探测失败:%s", exc, exc_info=True)
with _probe_guard: with _probe_guard:
_probe_state["error"] = str(exc)[:200] text = str(exc).strip() or "探测失败"
_probe_state["error"] = text[:200]
finally: finally:
with _probe_guard: with _probe_guard:
_probe_state["running"] = False _probe_state["running"] = False
@@ -597,8 +669,19 @@ def request_refresh() -> dict:
return payload return payload
def _reset_pool_running() -> None:
with _probe_guard:
_probe_state["running"] = False
with SessionLocal() as db:
row = db.get(ProxyPoolSync, 1)
if row is not None and row.running:
row.running = False
db.commit()
def start_proxy_pool() -> threading.Event: def start_proxy_pool() -> threading.Event:
global _stop global _stop
_reset_pool_running()
stop = threading.Event() stop = threading.Event()
_stop = stop _stop = stop