feat: 维护中国代理池并支持账号自动均匀使用
This commit is contained in:
@@ -0,0 +1,452 @@
|
||||
"""自有代理池:多上游汇聚、延迟检测、均匀分配、失效剔除。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.client import EUNIV, USER_AGENT
|
||||
from euniv.collectors import collect_all, is_china, source_title
|
||||
from euniv.db import SessionLocal
|
||||
from euniv.models import ProxyNode, ProxyPoolSync
|
||||
from euniv.proxy import build_proxy_url
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
FETCH_INTERVAL = 300
|
||||
LATENCY_LIMIT = 3.0
|
||||
LATENCY_LIMIT_MS = 3000
|
||||
PROBE_CONCURRENCY = 16
|
||||
MAX_PROBES = 80
|
||||
MAX_SWITCHES = 8
|
||||
PROBE_URL = EUNIV + "/"
|
||||
STATUS_ALIVE = "alive"
|
||||
STATUS_DEAD = "dead"
|
||||
STATUS_NEW = "new"
|
||||
|
||||
_ANONYMITY = {"elite": "高匿名", "anonymous": "匿名", "transparent": "透明"}
|
||||
_STATUS = {STATUS_ALIVE: "可用", STATUS_DEAD: "失效", STATUS_NEW: "待检测"}
|
||||
|
||||
_assign_lock = threading.Lock()
|
||||
_holds: dict[str, int] = {}
|
||||
_refresh_lock = threading.Lock()
|
||||
_stop: threading.Event | None = None
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _url(node: ProxyNode) -> str:
|
||||
return build_proxy_url(node.scheme, node.host, int(node.port))
|
||||
|
||||
|
||||
def _sync_row(db: Session) -> ProxyPoolSync:
|
||||
row = db.get(ProxyPoolSync, 1)
|
||||
if row is None:
|
||||
row = ProxyPoolSync(id=1)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
return row
|
||||
|
||||
|
||||
def _counts(db: Session) -> tuple[int, int, int]:
|
||||
rows = db.execute(select(ProxyNode.status, func.count()).group_by(ProxyNode.status)).all()
|
||||
tallies = {str(status): int(count) for status, count in rows}
|
||||
return tallies.get(STATUS_ALIVE, 0), tallies.get(STATUS_DEAD, 0), tallies.get(STATUS_NEW, 0)
|
||||
|
||||
|
||||
def _store_counts(db: Session, sync: ProxyPoolSync) -> None:
|
||||
sync.alive_count, sync.dead_count, sync.new_count = _counts(db)
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.isoformat()
|
||||
|
||||
|
||||
def _anonymity_label(value: str) -> str:
|
||||
return _ANONYMITY.get((value or "").strip().lower(), value or "—")
|
||||
|
||||
|
||||
def _country_label(value: str) -> str:
|
||||
text = (value or "").strip()
|
||||
if not text:
|
||||
return "—"
|
||||
if text.lower() in {"cn", "chn", "china"} or "中国" in text:
|
||||
return "中国"
|
||||
return text
|
||||
|
||||
|
||||
def _status_label(value: str) -> str:
|
||||
return _STATUS.get(value, value or "—")
|
||||
|
||||
|
||||
def view_item(node: ProxyNode) -> dict:
|
||||
return {
|
||||
"id": node.id,
|
||||
"scheme": node.scheme,
|
||||
"host": node.host,
|
||||
"port": int(node.port),
|
||||
"country": _country_label(node.country),
|
||||
"anonymity": _anonymity_label(node.anonymity),
|
||||
"source": source_title(node.source),
|
||||
"status": node.status,
|
||||
"status_text": _status_label(node.status),
|
||||
"latency_ms": node.latency_ms,
|
||||
"last_checked_at": _iso(node.last_checked_at),
|
||||
"last_ok_at": _iso(node.last_ok_at),
|
||||
"note": node.fail_reason or "",
|
||||
}
|
||||
|
||||
|
||||
def sync_view(db: Session) -> dict:
|
||||
sync = _sync_row(db)
|
||||
alive, dead, pending = _counts(db)
|
||||
return {
|
||||
"fetched_at": _iso(sync.fetched_at),
|
||||
"checked_at": _iso(sync.checked_at),
|
||||
"running": bool(sync.running),
|
||||
"message": sync.message or "",
|
||||
"alive": alive,
|
||||
"dead": dead,
|
||||
"pending": pending,
|
||||
"total": alive + dead + pending,
|
||||
}
|
||||
|
||||
|
||||
def page(db: Session, q: str = "", status: str = "", offset: int = 0, limit: int = 50) -> dict:
|
||||
bounded = min(max(int(limit), 1), 100)
|
||||
start = max(int(offset), 0)
|
||||
query = select(ProxyNode)
|
||||
count_query = select(func.count()).select_from(ProxyNode)
|
||||
kind = (status or "").strip().lower()
|
||||
if kind in {STATUS_ALIVE, STATUS_DEAD, STATUS_NEW}:
|
||||
query = query.where(ProxyNode.status == kind)
|
||||
count_query = count_query.where(ProxyNode.status == kind)
|
||||
text = (q or "").strip()
|
||||
if text:
|
||||
like = f"%{text}%"
|
||||
query = query.where(ProxyNode.host.like(like))
|
||||
count_query = count_query.where(ProxyNode.host.like(like))
|
||||
rank = case((ProxyNode.status == STATUS_ALIVE, 0), (ProxyNode.status == STATUS_NEW, 1), else_=2)
|
||||
query = query.order_by(rank, ProxyNode.latency_ms.is_(None), ProxyNode.latency_ms, ProxyNode.id)
|
||||
total = int(db.scalar(count_query) or 0)
|
||||
nodes = db.scalars(query.offset(start).limit(bounded)).all()
|
||||
payload = sync_view(db)
|
||||
payload["items"] = [view_item(node) for node in nodes]
|
||||
payload["total"] = total
|
||||
payload["offset"] = start
|
||||
payload["limit"] = bounded
|
||||
return payload
|
||||
|
||||
|
||||
def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
url = build_proxy_url(scheme, host, port)
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
with httpx.Client(
|
||||
proxy=url,
|
||||
timeout=LATENCY_LIMIT,
|
||||
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, ""
|
||||
except Exception as exc:
|
||||
latency = int((time.perf_counter() - started) * 1000)
|
||||
return False, latency, _short_reason(exc)
|
||||
|
||||
|
||||
def _short_reason(exc: BaseException) -> str:
|
||||
if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException)):
|
||||
return "超时"
|
||||
if isinstance(exc, (httpx.ProxyError, httpx.ConnectError)):
|
||||
return "无法连接"
|
||||
text = str(exc).strip() or type(exc).__name__
|
||||
return text[:200]
|
||||
|
||||
|
||||
def _find_node(db: Session, scheme: str, host: str, port: int) -> ProxyNode | None:
|
||||
return db.scalars(
|
||||
select(ProxyNode).where(
|
||||
ProxyNode.scheme == scheme,
|
||||
ProxyNode.host == host,
|
||||
ProxyNode.port == port,
|
||||
)
|
||||
).first()
|
||||
|
||||
|
||||
def _parse_proxy_url(value: str | None) -> tuple[str, str, int] | None:
|
||||
text = (value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
parsed = urlparse(text)
|
||||
host = parsed.hostname
|
||||
if not host or parsed.port is None:
|
||||
return None
|
||||
return (parsed.scheme or "http").lower(), host, int(parsed.port)
|
||||
|
||||
|
||||
def _evict_node(node_id: int) -> None:
|
||||
for employee_id, held in list(_holds.items()):
|
||||
if held == node_id:
|
||||
_holds.pop(employee_id, None)
|
||||
|
||||
|
||||
def acquire(employee_id: str) -> str | None:
|
||||
key = (employee_id or "").strip()
|
||||
if not key:
|
||||
return None
|
||||
with SessionLocal() as db, _assign_lock:
|
||||
held_id = _holds.get(key)
|
||||
if held_id:
|
||||
held = db.get(ProxyNode, held_id)
|
||||
if held is not None and held.status == STATUS_ALIVE:
|
||||
return _url(held)
|
||||
_holds.pop(key, None)
|
||||
nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all())
|
||||
if not nodes:
|
||||
return None
|
||||
load = {node.id: 0 for node in nodes}
|
||||
for node_id in _holds.values():
|
||||
if node_id in load:
|
||||
load[node_id] += 1
|
||||
nodes.sort(key=lambda node: (load[node.id], node.assigns, node.id))
|
||||
pick = nodes[0]
|
||||
_holds[key] = pick.id
|
||||
pick.assigns = int(pick.assigns or 0) + 1
|
||||
db.commit()
|
||||
return _url(pick)
|
||||
|
||||
|
||||
def release(employee_id: str) -> None:
|
||||
with _assign_lock:
|
||||
_holds.pop((employee_id or "").strip(), None)
|
||||
|
||||
|
||||
def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None:
|
||||
key = (employee_id or "").strip()
|
||||
parsed = _parse_proxy_url(proxy_url)
|
||||
with SessionLocal() as db, _assign_lock:
|
||||
node = None
|
||||
node_id = _holds.pop(key, None)
|
||||
if node_id:
|
||||
node = db.get(ProxyNode, node_id)
|
||||
if node is None and parsed is not None:
|
||||
node = _find_node(db, parsed[0], parsed[1], parsed[2])
|
||||
if node is None:
|
||||
return
|
||||
node.status = STATUS_DEAD
|
||||
node.fail_reason = (reason or "失效")[:200]
|
||||
node.last_checked_at = _now()
|
||||
_evict_node(node.id)
|
||||
db.commit()
|
||||
|
||||
|
||||
def refresh_once() -> dict:
|
||||
if not _refresh_lock.acquire(blocking=False):
|
||||
with SessionLocal() as db:
|
||||
return sync_view(db)
|
||||
try:
|
||||
return _refresh_body()
|
||||
finally:
|
||||
_refresh_lock.release()
|
||||
|
||||
|
||||
def _refresh_body() -> dict:
|
||||
with SessionLocal() as db:
|
||||
sync = _sync_row(db)
|
||||
sync.running = True
|
||||
sync.message = ""
|
||||
db.commit()
|
||||
try:
|
||||
candidates = collect_all()
|
||||
with SessionLocal() as db:
|
||||
sync = _sync_row(db)
|
||||
sync.fetched_at = _now()
|
||||
existing = {
|
||||
(node.scheme, node.host, int(node.port)): node
|
||||
for node in db.scalars(select(ProxyNode)).all()
|
||||
}
|
||||
new_ids: list[int] = []
|
||||
alive_ids: list[int] = []
|
||||
for item in candidates:
|
||||
if not is_china(item.country):
|
||||
continue
|
||||
key = (item.scheme, item.host, item.port)
|
||||
node = existing.get(key)
|
||||
if node is None:
|
||||
node = ProxyNode(
|
||||
scheme=item.scheme,
|
||||
host=item.host,
|
||||
port=item.port,
|
||||
country=item.country,
|
||||
anonymity=item.anonymity,
|
||||
source=item.source,
|
||||
status=STATUS_NEW,
|
||||
)
|
||||
db.add(node)
|
||||
db.flush()
|
||||
existing[key] = node
|
||||
new_ids.append(node.id)
|
||||
continue
|
||||
node.country = item.country or node.country
|
||||
node.anonymity = item.anonymity or node.anonymity
|
||||
node.source = item.source or node.source
|
||||
if node.status == STATUS_DEAD:
|
||||
continue
|
||||
if node.status == STATUS_NEW:
|
||||
new_ids.append(node.id)
|
||||
elif node.status == STATUS_ALIVE:
|
||||
alive_ids.append(node.id)
|
||||
for node in existing.values():
|
||||
if node.status == STATUS_ALIVE and node.id not in alive_ids and node.id not in new_ids:
|
||||
alive_ids.append(node.id)
|
||||
db.commit()
|
||||
probe_ids = _pick_probe_ids(db, new_ids, alive_ids)
|
||||
nodes = [db.get(ProxyNode, node_id) for node_id in probe_ids]
|
||||
snapshot = [
|
||||
(node.id, node.scheme, node.host, int(node.port))
|
||||
for node in nodes
|
||||
if node is not None
|
||||
]
|
||||
|
||||
results = _probe_many(snapshot)
|
||||
with SessionLocal() as db, _assign_lock:
|
||||
sync = _sync_row(db)
|
||||
for node_id, ok, latency, reason in results:
|
||||
node = db.get(ProxyNode, node_id)
|
||||
if node is None:
|
||||
continue
|
||||
if node.status == STATUS_DEAD:
|
||||
continue
|
||||
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 "失效"
|
||||
_evict_node(node.id)
|
||||
sync.checked_at = _now()
|
||||
sync.running = False
|
||||
_store_counts(db, sync)
|
||||
if sync.alive_count:
|
||||
sync.message = ""
|
||||
elif not candidates:
|
||||
sync.message = "没有获取到可用代理"
|
||||
else:
|
||||
sync.message = "当前没有可用代理"
|
||||
db.commit()
|
||||
return sync_view(db)
|
||||
except Exception:
|
||||
log.exception("代理池更新失败")
|
||||
with SessionLocal() as db:
|
||||
sync = _sync_row(db)
|
||||
sync.running = False
|
||||
sync.message = "没有更新"
|
||||
db.commit()
|
||||
return sync_view(db)
|
||||
|
||||
|
||||
def _pick_probe_ids(db: Session, new_ids: list[int], alive_ids: list[int]) -> list[int]:
|
||||
ordered: list[int] = []
|
||||
seen: set[int] = set()
|
||||
for node_id in new_ids:
|
||||
if node_id not in seen:
|
||||
seen.add(node_id)
|
||||
ordered.append(node_id)
|
||||
if len(ordered) >= MAX_PROBES:
|
||||
return ordered[:MAX_PROBES]
|
||||
alive_nodes = [
|
||||
node
|
||||
for node in (db.get(ProxyNode, node_id) for node_id in alive_ids)
|
||||
if node is not None
|
||||
]
|
||||
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:
|
||||
if node.id in seen:
|
||||
continue
|
||||
seen.add(node.id)
|
||||
ordered.append(node.id)
|
||||
if len(ordered) >= MAX_PROBES:
|
||||
break
|
||||
return ordered
|
||||
|
||||
|
||||
def _probe_many(nodes: list[tuple[int, str, str, int]]) -> list[tuple[int, bool, int, str]]:
|
||||
if not nodes:
|
||||
return []
|
||||
workers = min(PROBE_CONCURRENCY, len(nodes))
|
||||
results: list[tuple[int, bool, int, str]] = []
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = {
|
||||
pool.submit(probe, scheme, host, port): node_id
|
||||
for node_id, scheme, host, port in nodes
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
node_id = futures[future]
|
||||
try:
|
||||
ok, latency, reason = future.result()
|
||||
except Exception as exc:
|
||||
ok, latency, reason = False, LATENCY_LIMIT_MS, _short_reason(exc)
|
||||
results.append((node_id, ok, latency, reason))
|
||||
return results
|
||||
|
||||
|
||||
def request_refresh() -> dict:
|
||||
with SessionLocal() as db:
|
||||
sync = _sync_row(db)
|
||||
already = bool(sync.running)
|
||||
if not already:
|
||||
sync.running = True
|
||||
sync.message = ""
|
||||
db.commit()
|
||||
payload = sync_view(db)
|
||||
else:
|
||||
payload = sync_view(db)
|
||||
if not already:
|
||||
threading.Thread(target=refresh_once, name="euniv-proxy-pool-once", daemon=True).start()
|
||||
payload["running"] = True
|
||||
return payload
|
||||
|
||||
|
||||
def start_proxy_pool() -> threading.Event:
|
||||
global _stop
|
||||
stop = threading.Event()
|
||||
_stop = stop
|
||||
|
||||
def loop() -> None:
|
||||
if stop.wait(8):
|
||||
return
|
||||
while not stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
refresh_once()
|
||||
except Exception:
|
||||
log.exception("代理池更新失败")
|
||||
delay = max(1.0, FETCH_INTERVAL - (time.monotonic() - started))
|
||||
if stop.wait(delay):
|
||||
return
|
||||
|
||||
threading.Thread(target=loop, name="euniv-proxy-pool", daemon=True).start()
|
||||
return stop
|
||||
Reference in New Issue
Block a user