feat: 自动代理改为向接口领取,去掉 ProxyHub 和代理列表

This commit is contained in:
2026-11-17 21:15:41 +08:00
parent 19db13b360
commit 2fc5a0421b
14 changed files with 559 additions and 1743 deletions
+2 -1
View File
@@ -38,9 +38,10 @@ def fresh_database():
from euniv.login_limit import reset as reset_login
reset_login()
from euniv.proxy_pool import _holds
from euniv.proxy_pool import _fetches, _holds
_holds.clear()
_fetches.clear()
from euniv import autostudy as autostudy_mod
autostudy_mod._wanted.clear()
+160 -277
View File
@@ -1,228 +1,172 @@
import os
import httpx
from fastapi.testclient import TestClient
from euniv.collectors import ProxyCandidate, collect_all, is_china, parse_proxyhub_result
from euniv.crypto import encrypt_secret
from euniv.db import SessionLocal
from euniv.models import Account, ProxyNode
from euniv.proxy import apply as apply_proxy
from euniv.proxy import bind_url, is_proxy_failure, view_of
from euniv.proxy_pool import PROBE_URL, acquire, mark_failed, page, probe, refresh_once, release
from euniv.proxy_pool import _holds
INITIAL_PASSWORD = os.environ["EUNIV_ADMIN_PASSWORD"]
from euniv.models import Account
from euniv.proxy import is_proxy_failure
from euniv.proxy_pool import (
BATCH_SIZE,
MAX_FETCHES,
PROBE_URL,
SOURCE_PROTOCOL,
_fetch_batch,
_fetches,
_holds,
acquire,
force_direct,
probe,
release,
reset_budget,
)
def _node(host: str, port: int, status: str = "alive", scheme: str = "http", assigns: int = 0) -> ProxyNode:
node = ProxyNode(
scheme=scheme,
host=host,
port=port,
country="cn",
anonymity="elite",
source="proxyhub",
status=status,
latency_ms=200 if status == "alive" else None,
assigns=assigns,
)
with SessionLocal() as db:
db.add(node)
db.commit()
db.refresh(node)
return node
def _account(employee_id: str) -> None:
with SessionLocal() as db:
db.add(
Account(
employee_id=employee_id,
password_cipher=encrypt_secret("secret"),
credential_cipher="",
)
)
db.commit()
def test_parse_proxyhub_keeps_structured_rows() -> None:
payload = {
"jsonrpc": "2.0",
"id": 1,
"result": {
"isError": False,
"structuredContent": {
"proxies": [
{"ip": "1.1.1.1", "port": 8080, "country": "cn", "type": "http", "anonymity": "elite"},
{"ip": "2.2.2.2", "port": 1080, "country": "cn", "type": "socks5", "anonymity": "anonymous"},
],
"count": 2,
},
},
}
rows = parse_proxyhub_result(payload)
assert [(item.scheme, item.host, item.port, item.source) for item in rows] == [
("http", "1.1.1.1", 8080, "proxyhub"),
("socks5", "2.2.2.2", 1080, "proxyhub"),
]
def test_china_filter_and_collect_all(monkeypatch) -> None:
assert is_china("cn")
assert is_china("中国")
assert not is_china("us")
class Dummy:
name = "dummy"
def collect(self):
return [
ProxyCandidate("http", "1.1.1.1", 80, "cn", "elite", "dummy"),
ProxyCandidate("http", "8.8.8.8", 80, "us", "elite", "dummy"),
]
monkeypatch.setattr("euniv.collectors.collectors", lambda: [Dummy()])
items = collect_all()
assert [(item.host, item.country) for item in items] == [("1.1.1.1", "cn")]
def test_acquire_spreads_accounts_and_skips_dead() -> None:
def _clear() -> None:
_holds.clear()
first = _node("10.0.0.1", 8001)
second = _node("10.0.0.2", 8002)
_node("10.0.0.3", 8003, status="dead")
a = acquire("u1")
b = acquire("u2")
assert {a, b} == {"http://10.0.0.1:8001", "http://10.0.0.2:8002"}
c = acquire("u3")
assert c in {a, b}
mark_failed("u1", a, "无法连接")
again = acquire("u1")
assert again == b
with SessionLocal() as db:
dead_id = first.id if a.endswith(":8001") else second.id
dead = db.get(ProxyNode, dead_id)
assert dead is not None
assert dead.status == "dead"
assert acquire("u1") == again
_fetches.clear()
def test_fetch_batch_asks_for_eight_chinese_https_proxies(monkeypatch) -> None:
seen: dict = {}
class FakeResponse:
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,
},
}
class FakeClient:
def __init__(self, *_args, **_kwargs) -> None:
return None
def __enter__(self):
return self
def __exit__(self, *_args) -> bool:
return False
def get(self, url: str, params: dict | None = None):
seen["url"] = url
seen["params"] = params
return FakeResponse()
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"}
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)]]
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)
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 batches == []
def test_acquire_uses_eight_batches_then_direct(monkeypatch) -> None:
_clear()
calls = {"n": 0}
def fetch() -> list[tuple[str, int]]:
calls["n"] += 1
return [(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, "无法连接"))
assert acquire("u1") is None
assert calls["n"] == MAX_FETCHES
assert acquire("u1") is None
assert calls["n"] == MAX_FETCHES
def test_failed_proxy_fetches_the_next_batch_until_budget(monkeypatch) -> None:
_clear()
calls = {"n": 0}
def fetch() -> list[tuple[str, int]]:
calls["n"] += 1
return [(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, ""))
first = acquire("u1")
assert first == "http://1.2.3.1:8000"
force_direct("u1")
assert acquire("u1") is None
assert calls["n"] == 1
reset_budget("u1")
assert acquire("u1") == "http://1.2.3.2:8000"
def test_direct_recheck_keeps_valid_credential_without_login(monkeypatch) -> None:
from euniv.autostudy import _continue_direct
class Fake:
login_called = False
def __init__(self, employee_id: str, password: str, proxy: str | None = None) -> None:
assert proxy is None
self.client = self
self.cookies = self
self.jar: list = []
self._profile = {"userId": "u", "accountId": employee_id}
def restore(self, credential: dict) -> None:
assert credential["yxt_token"] == "saved"
def credential_alive(self) -> bool:
return True
def _ensure_site(self) -> str:
return ""
def session_token(self) -> str:
return "saved"
def login(self, manual: bool = False) -> dict:
Fake.login_called = True
raise AssertionError("凭据仍有效,不应重新登录")
def close(self) -> None:
return None
monkeypatch.setattr("euniv.autostudy.EunivClient", Fake)
monkeypatch.setattr("euniv.autostudy._stored_credential", lambda _employee_id: {"yxt_token": "saved"})
monkeypatch.setattr("euniv.proxy_pool.force_direct", lambda _employee_id: None)
token, _user_id, _org_id, _cookies, proxy, reason = _continue_direct("100", "pw")
assert token == "saved"
assert proxy is None
assert reason == ""
assert Fake.login_called is False
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.probe", lambda *_args: (True, 15, ""))
assert acquire("u1") == "http://8.8.4.4:8080"
release("u1")
release("u2")
release("u3")
assert "u1" not in _holds
assert "u1" not in _fetches
def test_empty_pool_returns_direct() -> None:
_holds.clear()
_node("10.0.0.9", 9, status="dead")
assert acquire("nobody") is None
def test_bind_url_uses_pool_or_manual() -> None:
_holds.clear()
_node("10.0.0.4", 8004)
_account("pool-user")
_account("manual-user")
with SessionLocal() as db:
pool_user = db.get(Account, "pool-user")
manual_user = db.get(Account, "manual-user")
assert pool_user is not None and manual_user is not None
apply_proxy(pool_user, "pool")
apply_proxy(manual_user, "http", "1.1.1.1", 7890)
db.commit()
db.refresh(pool_user)
db.refresh(manual_user)
assert view_of(pool_user)["scheme"] == "pool"
assert bind_url(pool_user) == "http://10.0.0.4:8004"
assert bind_url(manual_user) == "http://1.1.1.1:7890"
apply_proxy(pool_user, "off")
db.commit()
db.refresh(pool_user)
assert bind_url(pool_user) is None
def test_refresh_marks_slow_and_keeps_fast(monkeypatch) -> None:
_holds.clear()
monkeypatch.setattr(
"euniv.proxy_pool.collect_all",
lambda: [
ProxyCandidate("http", "1.1.1.1", 80, "cn", "elite", "proxyhub"),
ProxyCandidate("http", "2.2.2.2", 80, "cn", "elite", "proxyhub"),
ProxyCandidate("http", "4.4.4.4", 80, "cn", "elite", "proxyhub"),
ProxyCandidate("http", "3.3.3.3", 80, "us", "elite", "proxyhub"),
],
)
def fake_probe(scheme: str, host: str, port: int):
if host == "1.1.1.1":
return True, 800, ""
return False, 4000, "超时"
monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe)
payload = refresh_once()
assert payload["alive"] == 1
assert payload["dead"] == 2
assert payload["message"] == ""
with SessionLocal() as db:
listed = page(db)
hosts = {item["host"]: item for item in listed["items"]}
assert hosts["1.1.1.1"]["status"] == "alive"
assert hosts["1.1.1.1"]["latency_ms"] == 800
assert hosts["2.2.2.2"]["status"] == "dead"
assert "3.3.3.3" not in hosts
def test_failed_proxy_is_not_reprobed(monkeypatch) -> None:
_holds.clear()
dead = _node("9.9.9.9", 99, status="dead")
monkeypatch.setattr(
"euniv.proxy_pool.collect_all",
lambda: [ProxyCandidate("http", "9.9.9.9", 99, "cn", "elite", "proxyhub")],
)
called = []
def fake_probe(scheme: str, host: str, port: int):
called.append(host)
return True, 10, ""
monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe)
refresh_once()
assert called == []
with SessionLocal() as db:
node = db.get(ProxyNode, dead.id)
assert node is not None
assert node.status == "dead"
def test_old_dead_proxy_is_reprobed(monkeypatch) -> None:
from datetime import datetime, timedelta, timezone
_holds.clear()
stale = _node("8.8.8.8", 88, status="dead")
with SessionLocal() as db:
node = db.get(ProxyNode, stale.id)
assert node is not None
node.last_checked_at = datetime.now(timezone.utc) - timedelta(hours=1)
db.commit()
monkeypatch.setattr(
"euniv.proxy_pool.collect_all",
lambda: [ProxyCandidate("http", "8.8.8.8", 88, "cn", "elite", "proxyhub")],
)
called: list[str] = []
def fake_probe(scheme: str, host: str, port: int):
called.append(host)
return True, 20, ""
monkeypatch.setattr("euniv.proxy_pool.probe", fake_probe)
refresh_once()
assert called == ["8.8.8.8"]
with SessionLocal() as db:
node = db.get(ProxyNode, stale.id)
assert node is not None
assert node.status == "alive"
def test_probe_averages_euniv_related_sites(monkeypatch) -> None:
def test_probe_reaches_euniv_home(monkeypatch) -> None:
seen: list[str] = []
class FakeResponse:
@@ -269,43 +213,12 @@ def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None:
ticks = iter([0.0, 0.008])
monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient)
monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks))
ok, latency, reason = probe("socks4", "10.0.0.9", 1080)
ok, latency, reason = probe("http", "1.1.1.1", 8080)
assert ok is False
assert latency == 8
assert reason == "无法连接"
def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None:
import euniv.api as api_module
_holds.clear()
one = _node("10.0.0.7", 8007)
two = _node("10.0.0.8", 8008, status="new")
monkeypatch.setattr("euniv.proxy_pool.probe", lambda scheme, host, port: (True, 321 if host.endswith("7") else 654, ""))
client = TestClient(api_module.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
single = client.post(f"/api/admin/proxies/{one.id}/probe")
assert single.status_code == 200
assert single.json()["latency_ms"] == 321
assert single.json()["status"] == "alive"
bulk = client.post("/api/admin/proxies/probe", json={"ids": [two.id]})
assert bulk.status_code == 200
assert bulk.json()["running"] is True
finished = {"running": True}
for _ in range(40):
finished = client.get("/api/admin/proxies/probe").json()
if finished["running"] is False:
break
import time
time.sleep(0.05)
assert finished["running"] is False
listed = client.get("/api/admin/proxies").json()
probed = next(item for item in listed["items"] if item["id"] == two.id)
assert probed["latency_ms"] == 654
missing = client.post("/api/admin/proxies/99999/probe")
assert missing.status_code == 404
def test_is_proxy_failure_detects_connect_errors() -> None:
assert is_proxy_failure(httpx.ConnectError("boom"))
assert is_proxy_failure(httpx.ConnectTimeout("late"))
@@ -315,37 +228,6 @@ def test_is_proxy_failure_detects_connect_errors() -> None:
assert not is_proxy_failure(RuntimeError("登录需要重新验证"))
def test_admin_proxy_page_and_pool_assignment() -> None:
import euniv.api as api_module
_holds.clear()
_node("10.0.0.5", 8005)
_account("a-user")
_account("b-user")
client = TestClient(api_module.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
listed = client.get("/api/admin/proxies")
assert listed.status_code == 200
body = listed.json()
assert body["alive"] == 1
assert body["items"][0]["host"] == "10.0.0.5"
assert body["items"][0]["status_text"] == "可用"
saved = client.put(
"/api/admin/users/study-settings",
json={"employee_ids": ["a-user", "b-user"], "scheme": "pool"},
)
assert saved.status_code == 200
users = client.get("/api/admin/users").json()
one = next(item for item in users if item["employee_id"] == "a-user")
two = next(item for item in users if item["employee_id"] == "b-user")
assert one["has_proxy"] is True
assert one["proxy"] == "自动"
assert two["proxy"] == "自动"
detail = client.get("/api/admin/users/a-user/proxy")
assert detail.json()["scheme"] == "pool"
assert detail.json()["enabled"] is True
def test_user_can_enable_pool_proxy(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
@@ -406,3 +288,4 @@ def test_user_can_enable_pool_proxy(monkeypatch) -> None:
account = db.get(Account, "6650000146")
assert account is not None
assert account.use_proxy_pool is True