feat: 立即开始停止学习并整理学时历史与界面

This commit is contained in:
2026-11-15 04:16:40 +08:00
parent ce2d6e08dd
commit f0a2bdd854
25 changed files with 1748 additions and 580 deletions
+97 -11
View File
@@ -13,7 +13,7 @@ import httpx
from sqlalchemy import case, func, select
from sqlalchemy.orm import Session
from euniv.client import EUNIV, USER_AGENT
from euniv.client import EUNIV, STUDY_API, USER_AGENT, YXT_API
from euniv.collectors import collect_all, is_china, source_title
from euniv.db import SessionLocal
from euniv.models import ProxyNode, ProxyPoolSync
@@ -21,6 +21,10 @@ from euniv.proxy import build_proxy_url
log = logging.getLogger(__name__)
class ProxyProbeError(ValueError):
"""延迟测试目标不存在。"""
FETCH_INTERVAL = 300
LATENCY_LIMIT = 3.0
LATENCY_LIMIT_MS = 3000
@@ -28,6 +32,11 @@ PROBE_CONCURRENCY = 16
MAX_PROBES = 80
MAX_SWITCHES = 8
PROBE_URL = EUNIV + "/"
PROBE_URLS = (
EUNIV + "/",
STUDY_API + "/",
YXT_API + "/",
)
STATUS_ALIVE = "alive"
STATUS_DEAD = "dead"
STATUS_NEW = "new"
@@ -154,7 +163,8 @@ def page(db: Session, q: str = "", status: str = "", offset: int = 0, limit: int
def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
url = build_proxy_url(scheme, host, port)
started = time.perf_counter()
samples: list[int] = []
reasons: list[str] = []
try:
with httpx.Client(
proxy=url,
@@ -162,16 +172,29 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
follow_redirects=True,
headers={"User-Agent": USER_AGENT},
) as client:
response = client.get(PROBE_URL)
latency = int((time.perf_counter() - started) * 1000)
if latency > LATENCY_LIMIT_MS:
return False, latency, "超时"
if response.status_code >= 500:
return False, latency, f"HTTP {response.status_code}"
return True, latency, ""
for target in PROBE_URLS:
started = time.perf_counter()
try:
response = client.get(target)
latency = int((time.perf_counter() - started) * 1000)
if response.status_code >= 500:
samples.append(max(latency, LATENCY_LIMIT_MS))
reasons.append(f"HTTP {response.status_code}")
continue
samples.append(latency)
except Exception as exc:
samples.append(int((time.perf_counter() - started) * 1000) or LATENCY_LIMIT_MS)
reasons.append(_short_reason(exc))
except Exception as exc:
latency = int((time.perf_counter() - started) * 1000)
return False, latency, _short_reason(exc)
return False, LATENCY_LIMIT_MS, _short_reason(exc)
if not samples:
return False, LATENCY_LIMIT_MS, reasons[0] if reasons else "无法连接"
average = int(round(sum(samples) / len(samples)))
if reasons:
return False, average, reasons[0]
if average > LATENCY_LIMIT_MS:
return False, average, "超时"
return True, average, ""
def _short_reason(exc: BaseException) -> str:
@@ -413,6 +436,69 @@ def _probe_many(nodes: list[tuple[int, str, str, int]]) -> list[tuple[int, bool,
return results
def _apply_probe(node: ProxyNode, ok: bool, latency: int, reason: str) -> None:
node.last_checked_at = _now()
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 "失效")[:200]
_evict_node(node.id)
def probe_one(node_id: int) -> dict:
with SessionLocal() as db:
node = db.get(ProxyNode, node_id)
if node is None:
raise ProxyProbeError("代理不存在")
snapshot = (node.id, node.scheme, node.host, int(node.port))
ok, latency, reason = probe(snapshot[1], snapshot[2], snapshot[3])
with SessionLocal() as db, _assign_lock:
node = db.get(ProxyNode, node_id)
if node is None:
raise ProxyProbeError("代理不存在")
_apply_probe(node, ok, latency, reason)
db.commit()
return view_item(node)
def probe_ids(ids: list[int] | None = None) -> dict:
with SessionLocal() as db:
if ids:
wanted = []
seen: set[int] = set()
for raw in ids:
node_id = int(raw)
if node_id in seen:
continue
seen.add(node_id)
wanted.append(node_id)
nodes = [
node
for node in (db.get(ProxyNode, node_id) for node_id in wanted)
if node is not None
]
if len(nodes) != len(wanted):
raise ProxyProbeError("代理不存在")
else:
nodes = list(db.scalars(select(ProxyNode).order_by(ProxyNode.id)).all())
snapshot = [(node.id, node.scheme, node.host, int(node.port)) for node in nodes]
results = _probe_many(snapshot)
items = []
with SessionLocal() as db, _assign_lock:
for node_id, ok, latency, reason in results:
node = db.get(ProxyNode, node_id)
if node is None:
continue
_apply_probe(node, ok, latency, reason)
items.append(view_item(node))
db.commit()
return {"ok": True, "count": len(items), "items": items}
def request_refresh() -> dict:
with SessionLocal() as db:
sync = _sync_row(db)