diff --git a/backend/euniv/proxy_pool.py b/backend/euniv/proxy_pool.py index f6dc513..be44d4a 100644 --- a/backend/euniv/proxy_pool.py +++ b/backend/euniv/proxy_pool.py @@ -1,10 +1,10 @@ -"""自动代理:一个任务最多向 proxy.scdn.io 领取 8 批中国代理,每批 8 个。 +"""自动代理:一个任务最多向 proxy.scdn.io 领取 8 批中国代理。 -每批按顺序检查,第一个能打开学习平台的就用。学习过程中这个代理失效,再领下一批。 -8 批都用完任务还没结束,就改走本机网络。 +每批先要 8 个 SOCKS5,再要 8 个 HTTP,最后要 8 个 HTTPS。按这个顺序检查,第一个能打开学习平台的就用。 +学习过程中这个代理失效,再领下一批。8 批都用完任务还没结束,就改走本机网络。 -接口的 https 表示这个代理能访问 HTTPS 网站。这类节点本身仍是 HTTP 代理, -用 HTTP CONNECT 转发。SOCKS4 常因 ident 校验被拒绝,不用。 +接口的 https 表示这个代理能访问 HTTPS 网站,连接方式仍是 HTTP 转发。 +SOCKS4 常因 ident 校验被拒绝,不用。 """ from __future__ import annotations @@ -27,8 +27,8 @@ LATENCY_LIMIT = 3.0 LATENCY_LIMIT_MS = 3000 PROBE_URL = EUNIV + "/" SOURCE_URL = "https://proxy.scdn.io/api/get_proxy.php" -SOURCE_PROTOCOL = "https" -CLIENT_SCHEME = "http" +# 先试 SOCKS5,再试 HTTP。接口里的 https 仍是 HTTP 代理,用 HTTP CONNECT 打开学习平台。 +SOURCE_PROTOCOLS = (("socks5", "socks5"), ("http", "http"), ("https", "http")) _lock = threading.Lock() _holds: dict[str, str] = {} @@ -115,18 +115,7 @@ def _parse_endpoint(value: object) -> tuple[str, int] | None: return host, port -def _fetch_batch() -> list[tuple[str, int]]: - """向接口要一批中国代理。接口失败时返回空列表,这一批仍然算一次领取。""" - try: - with httpx.Client(timeout=10, trust_env=False, verify=shared_tls()) as client: - response = client.get( - SOURCE_URL, - params={"protocol": SOURCE_PROTOCOL, "count": BATCH_SIZE, "country_code": "CN"}, - ) - payload = response.json() - except Exception: - log.warning("代理接口没有获取到", exc_info=True) - return [] +def _read_proxies(payload: object) -> list[tuple[str, int]]: if not isinstance(payload, dict) or payload.get("code") != 200: return [] data = payload.get("data") @@ -134,18 +123,42 @@ def _fetch_batch() -> list[tuple[str, int]]: if not isinstance(proxies, list): return [] found: list[tuple[str, int]] = [] - seen: set[tuple[str, int]] = set() for item in proxies: parsed = _parse_endpoint(item) - if parsed is None or parsed in seen: + if parsed is None: continue - seen.add(parsed) found.append(parsed) if len(found) >= BATCH_SIZE: break return found +def _fetch_batch() -> list[tuple[str, str, int]]: + """向接口要一批中国代理。顺序是 SOCKS5、HTTP、HTTPS。接口失败时这一批仍然算一次领取。""" + found: list[tuple[str, str, int]] = [] + seen: set[tuple[str, int]] = set() + try: + with httpx.Client(timeout=10, trust_env=False, verify=shared_tls()) as client: + for protocol, scheme in SOURCE_PROTOCOLS: + try: + response = client.get( + SOURCE_URL, + params={"protocol": protocol, "count": BATCH_SIZE, "country_code": "CN"}, + ) + rows = _read_proxies(response.json()) + except Exception: + log.warning("代理接口没有获取到 %s", protocol, exc_info=True) + continue + for host, port in rows: + if (host, port) in seen: + continue + seen.add((host, port)) + found.append((scheme, host, port)) + except Exception: + log.warning("代理接口没有获取到", exc_info=True) + return found + + def force_direct(employee_id: str) -> None: """这个任务不再领代理,之后的访问走本机网络。""" key = (employee_id or "").strip() @@ -183,12 +196,12 @@ def acquire(employee_id: str) -> str | None: return None _fetches[key] = used + 1 # 同批按顺序测,第一个能打开学习平台的立即使用,不再测后面的。 - for host, port in _fetch_batch(): - ok, _latency, reason = probe(CLIENT_SCHEME, host, port) + for scheme, host, port in _fetch_batch(): + ok, _latency, reason = probe(scheme, host, port) if not ok: log.info("代理 %s:%s 不能访问学习平台:%s", host, port, reason or "失效") continue - url = build_proxy_url(CLIENT_SCHEME, host, port) + url = build_proxy_url(scheme, host, port) with _lock: current = _holds.get(key) if current: diff --git a/backend/tests/test_proxy_pool.py b/backend/tests/test_proxy_pool.py index 50f032a..f58be6a 100644 --- a/backend/tests/test_proxy_pool.py +++ b/backend/tests/test_proxy_pool.py @@ -9,7 +9,7 @@ from euniv.proxy_pool import ( BATCH_SIZE, MAX_FETCHES, PROBE_URL, - SOURCE_PROTOCOL, + SOURCE_PROTOCOLS, _fetch_batch, _fetches, _holds, @@ -26,19 +26,20 @@ def _clear() -> None: _fetches.clear() -def test_fetch_batch_asks_for_eight_chinese_https_proxies(monkeypatch) -> None: - seen: dict = {} +def test_fetch_batch_asks_for_socks5_then_http_then_https(monkeypatch) -> None: + calls: list[dict] = [] class FakeResponse: + def __init__(self, protocol: str) -> None: + self.protocol = protocol + def json(self) -> dict: - return { - "code": 200, - "message": "success", - "data": { - "proxies": ["1.2.3.4:8080", "10.0.0.1:3128", "bad", "8.8.8.8:9"], - "count": 4, - }, - } + proxies = { + "socks5": ["1.2.3.4:1080"], + "http": ["9.9.9.9:8080"], + "https": ["1.2.3.4:1080", "8.8.8.8:8080", "10.0.0.1:1"], + }[self.protocol] + return {"code": 200, "message": "success", "data": {"proxies": proxies, "count": len(proxies)}} class FakeClient: def __init__(self, *_args, **_kwargs) -> None: @@ -51,31 +52,35 @@ def test_fetch_batch_asks_for_eight_chinese_https_proxies(monkeypatch) -> None: return False def get(self, url: str, params: dict | None = None): - seen["url"] = url - seen["params"] = params - return FakeResponse() + calls.append({"url": url, "params": params or {}}) + return FakeResponse(str((params or {}).get("protocol"))) monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient) - assert _fetch_batch() == [("1.2.3.4", 8080), ("8.8.8.8", 9)] - assert seen["url"].endswith("/api/get_proxy.php") - assert seen["params"] == {"protocol": SOURCE_PROTOCOL, "count": BATCH_SIZE, "country_code": "CN"} + assert _fetch_batch() == [ + ("socks5", "1.2.3.4", 1080), + ("http", "9.9.9.9", 8080), + ("http", "8.8.8.8", 8080), + ] + assert [item["params"]["protocol"] for item in calls] == [protocol for protocol, _scheme in SOURCE_PROTOCOLS] + assert all(item["url"].endswith("/api/get_proxy.php") for item in calls) + assert all(item["params"]["count"] == BATCH_SIZE and item["params"]["country_code"] == "CN" for item in calls) def test_acquire_stops_at_the_first_usable_proxy(monkeypatch) -> None: _clear() - batches = [[("1.1.1.1", 1), ("2.2.2.2", 2), ("3.3.3.3", 3)]] + batches = [[("socks5", "1.1.1.1", 1), ("socks5", "2.2.2.2", 2), ("http", "3.3.3.3", 3)]] probed: list[str] = [] monkeypatch.setattr("euniv.proxy_pool._fetch_batch", lambda: list(batches.pop(0))) - def fake_probe(_scheme: str, host: str, _port: int): - probed.append(host) + def fake_probe(scheme: str, host: str, _port: int): + probed.append(f"{scheme}:{host}") return host == "2.2.2.2", 10, "" monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe) - assert acquire("u1") == "http://2.2.2.2:2" - assert probed == ["1.1.1.1", "2.2.2.2"] - assert acquire("u1") == "http://2.2.2.2:2" + assert acquire("u1") == "socks5://2.2.2.2:2" + assert probed == ["socks5:1.1.1.1", "socks5:2.2.2.2"] + assert acquire("u1") == "socks5://2.2.2.2:2" assert batches == [] @@ -85,7 +90,7 @@ def test_acquire_uses_eight_batches_then_direct(monkeypatch) -> None: def fetch() -> list[tuple[str, int]]: calls["n"] += 1 - return [(f"1.2.3.{calls['n']}", 8000)] + return [("http", f"1.2.3.{calls['n']}", 8000)] monkeypatch.setattr("euniv.proxy_pool._fetch_batch", fetch) monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (False, 8, "无法连接")) @@ -101,7 +106,7 @@ def test_failed_proxy_fetches_the_next_batch_until_budget(monkeypatch) -> None: def fetch() -> list[tuple[str, int]]: calls["n"] += 1 - return [(f"1.2.3.{calls['n']}", 8000)] + return [("http", f"1.2.3.{calls['n']}", 8000)] monkeypatch.setattr("euniv.proxy_pool._fetch_batch", fetch) monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (True, 20, "")) @@ -158,7 +163,7 @@ def test_direct_recheck_keeps_valid_credential_without_login(monkeypatch) -> Non def test_release_lets_the_next_task_fetch_again(monkeypatch) -> None: _clear() - monkeypatch.setattr("euniv.proxy_pool._fetch_batch", lambda: [("8.8.4.4", 8080)]) + monkeypatch.setattr("euniv.proxy_pool._fetch_batch", lambda: [("http", "8.8.4.4", 8080)]) monkeypatch.setattr("euniv.proxy_pool.probe", lambda *_args: (True, 15, "")) assert acquire("u1") == "http://8.8.4.4:8080" release("u1")