feat: 自动代理改为向接口领取,去掉 ProxyHub 和代理列表
This commit is contained in:
+128
-644
@@ -1,178 +1,38 @@
|
||||
"""自有代理池:多上游汇聚、延迟检测、均匀分配、失效剔除。"""
|
||||
"""自动代理:一个任务最多向 proxy.scdn.io 领取 8 批中国代理,每批 8 个。
|
||||
|
||||
每批按顺序检查,第一个能打开学习平台的就用。学习过程中这个代理失效,再领下一批。
|
||||
8 批都用完任务还没结束,就改走本机网络。
|
||||
|
||||
接口的 https 表示这个代理能访问 HTTPS 网站。这类节点本身仍是 HTTP 代理,
|
||||
用 HTTP CONNECT 转发。SOCKS4 常因 ident 校验被拒绝,不用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import case, func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
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
|
||||
from euniv.proxy import build_proxy_url, sync_httpx_client
|
||||
from euniv.client import EUNIV, USER_AGENT
|
||||
from euniv.proxy import ProxyError, assert_public_host, build_proxy_url, shared_tls, sync_httpx_client
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ProxyProbeError(ValueError):
|
||||
"""延迟测试目标不存在。"""
|
||||
|
||||
FETCH_INTERVAL = 300
|
||||
MAX_FETCHES = 8
|
||||
MAX_SWITCHES = MAX_FETCHES
|
||||
BATCH_SIZE = 8
|
||||
LATENCY_LIMIT = 3.0
|
||||
LATENCY_LIMIT_MS = 3000
|
||||
PROBE_CONCURRENCY = 16
|
||||
MAX_PROBES = 80
|
||||
PROBE_BATCH_TIMEOUT = 20.0
|
||||
ALIVE_REPROBE_SLOTS = 20
|
||||
MAX_SWITCHES = 8
|
||||
PROBE_URL = EUNIV + "/"
|
||||
PROBE_URLS = (
|
||||
EUNIV + "/",
|
||||
STUDY_API + "/",
|
||||
YXT_API + "/",
|
||||
)
|
||||
STATUS_ALIVE = "alive"
|
||||
STATUS_DEAD = "dead"
|
||||
STATUS_NEW = "new"
|
||||
SOURCE_URL = "https://proxy.scdn.io/api/get_proxy.php"
|
||||
SOURCE_PROTOCOL = "https"
|
||||
CLIENT_SCHEME = "http"
|
||||
|
||||
_ANONYMITY = {"elite": "高匿名", "anonymous": "匿名", "transparent": "透明"}
|
||||
_STATUS = {STATUS_ALIVE: "可用", STATUS_DEAD: "失效", STATUS_NEW: "待检测"}
|
||||
|
||||
_assign_lock = threading.Lock()
|
||||
_holds: dict[str, int] = {}
|
||||
_refresh_lock = threading.Lock()
|
||||
_probe_guard = threading.Lock()
|
||||
_probe_state = {"running": False, "count": 0, "error": ""}
|
||||
|
||||
|
||||
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 not None:
|
||||
return row
|
||||
row = ProxyPoolSync(id=1)
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
_lock = threading.Lock()
|
||||
_holds: dict[str, str] = {}
|
||||
_fetches: dict[str, int] = {}
|
||||
|
||||
|
||||
def _elapsed_ms(started: float) -> int:
|
||||
@@ -190,19 +50,18 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
) as client:
|
||||
for target in (PROBE_URL,):
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
response = client.get(target)
|
||||
latency = _elapsed_ms(started)
|
||||
if response.status_code >= 500:
|
||||
samples.append(latency)
|
||||
reasons.append(f"HTTP {response.status_code}")
|
||||
continue
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
response = client.get(PROBE_URL)
|
||||
latency = _elapsed_ms(started)
|
||||
if response.status_code >= 500:
|
||||
samples.append(latency)
|
||||
except Exception as exc:
|
||||
samples.append(_elapsed_ms(started))
|
||||
reasons.append(_short_reason(exc))
|
||||
reasons.append(f"HTTP {response.status_code}")
|
||||
else:
|
||||
samples.append(latency)
|
||||
except Exception as exc:
|
||||
samples.append(_elapsed_ms(started))
|
||||
reasons.append(_short_reason(exc))
|
||||
except Exception as exc:
|
||||
return False, 0, _short_reason(exc)
|
||||
average = int(round(sum(samples) / len(samples)))
|
||||
@@ -213,21 +72,6 @@ def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]:
|
||||
return True, average, ""
|
||||
|
||||
|
||||
def _direct_reaches_target() -> bool:
|
||||
"""节点全灭时对照直连,区分代理故障和目标站故障。"""
|
||||
try:
|
||||
with sync_httpx_client(
|
||||
None,
|
||||
timeout=LATENCY_LIMIT,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
) as client:
|
||||
response = client.get(PROBE_URL)
|
||||
return response.status_code < 500
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _clip_reason(reason: str, fallback: str = "失效") -> str:
|
||||
text = (reason or "").strip() or fallback
|
||||
if len(text) <= 200:
|
||||
@@ -252,480 +96,120 @@ def _short_reason(exc: BaseException) -> str:
|
||||
return _clip_reason(stored)
|
||||
|
||||
|
||||
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:
|
||||
def _parse_endpoint(value: object) -> tuple[str, int] | None:
|
||||
text = str(value or "").strip()
|
||||
if not text or "://" in text or text.count(":") != 1:
|
||||
return None
|
||||
parsed = urlparse(text)
|
||||
host = parsed.hostname
|
||||
if not host or parsed.port is None:
|
||||
host, raw_port = text.rsplit(":", 1)
|
||||
host = host.strip()
|
||||
try:
|
||||
port = int(raw_port)
|
||||
except ValueError:
|
||||
return None
|
||||
return (parsed.scheme or "http").lower(), host, int(parsed.port)
|
||||
if not host or not 1 <= port <= 65535:
|
||||
return None
|
||||
try:
|
||||
assert_public_host(host)
|
||||
except ProxyError:
|
||||
return None
|
||||
return host, 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 _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 []
|
||||
if not isinstance(payload, dict) or payload.get("code") != 200:
|
||||
return []
|
||||
data = payload.get("data")
|
||||
proxies = data.get("proxies") if isinstance(data, dict) else None
|
||||
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:
|
||||
continue
|
||||
seen.add(parsed)
|
||||
found.append(parsed)
|
||||
if len(found) >= BATCH_SIZE:
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def force_direct(employee_id: str) -> None:
|
||||
"""这个任务不再领代理,之后的访问走本机网络。"""
|
||||
key = (employee_id or "").strip()
|
||||
if not key:
|
||||
return
|
||||
with _lock:
|
||||
_holds.pop(key, None)
|
||||
_fetches[key] = MAX_FETCHES
|
||||
|
||||
|
||||
def reset_budget(employee_id: str) -> None:
|
||||
"""新的学习任务重新计算 8 次领取。"""
|
||||
key = (employee_id or "").strip()
|
||||
if not key:
|
||||
return
|
||||
with _lock:
|
||||
_holds.pop(key, None)
|
||||
_fetches.pop(key, None)
|
||||
|
||||
|
||||
def acquire(employee_id: str) -> str | None:
|
||||
"""给这个账号一个已经能打开学习平台的代理。8 批都没有就返回空,调用方改走直连。"""
|
||||
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)
|
||||
if held is not None:
|
||||
held.assigns = _occupancy(held.id)
|
||||
nodes = list(db.scalars(select(ProxyNode).where(ProxyNode.status == STATUS_ALIVE)).all())
|
||||
if not nodes:
|
||||
db.commit()
|
||||
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
|
||||
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]
|
||||
_holds[key] = pick.id
|
||||
pick.assigns = load[pick.id] + 1
|
||||
db.commit()
|
||||
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)
|
||||
with _lock:
|
||||
held = _holds.get(key)
|
||||
if held:
|
||||
return held
|
||||
while True:
|
||||
with _lock:
|
||||
used = _fetches.get(key, 0)
|
||||
if used >= MAX_FETCHES:
|
||||
log.info("账号 %s 已领取 %s 批代理,改为直连", key, MAX_FETCHES)
|
||||
return None
|
||||
_fetches[key] = used + 1
|
||||
# 同批按顺序测,第一个能打开学习平台的立即使用,不再测后面的。
|
||||
for host, port in _fetch_batch():
|
||||
ok, _latency, reason = probe(CLIENT_SCHEME, host, port)
|
||||
if not ok:
|
||||
log.info("代理 %s:%s 不能访问学习平台:%s", host, port, reason or "失效")
|
||||
continue
|
||||
url = build_proxy_url(CLIENT_SCHEME, host, port)
|
||||
with _lock:
|
||||
current = _holds.get(key)
|
||||
if current:
|
||||
return current
|
||||
_holds[key] = url
|
||||
return url
|
||||
|
||||
|
||||
def release(employee_id: str) -> None:
|
||||
key = (employee_id or "").strip()
|
||||
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 retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool:
|
||||
"""立刻复测当前节点。还通就继续用;不通就标死。"""
|
||||
parsed = _parse_proxy_url(proxy_url)
|
||||
if parsed is None:
|
||||
mark_failed(employee_id, proxy_url, reason)
|
||||
return True
|
||||
ok, _latency, why = probe(parsed[0], parsed[1], parsed[2])
|
||||
if ok:
|
||||
return False
|
||||
mark_failed(employee_id, proxy_url, why or reason)
|
||||
return True
|
||||
reset_budget(employee_id)
|
||||
|
||||
|
||||
def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None:
|
||||
"""这个账号正在用的代理已经失败。领取次数保留,下次再领一批。"""
|
||||
del proxy_url, reason
|
||||
key = (employee_id or "").strip()
|
||||
parsed = _parse_proxy_url(proxy_url)
|
||||
with SessionLocal() as db, _assign_lock:
|
||||
node = _find_node(db, parsed[0], parsed[1], parsed[2]) if parsed is not None else None
|
||||
held = _holds.get(key)
|
||||
if node is None and held is not None:
|
||||
node = db.get(ProxyNode, held)
|
||||
if node is None:
|
||||
return
|
||||
if held == node.id:
|
||||
_holds.pop(key, None)
|
||||
node.status = STATUS_DEAD
|
||||
node.fail_reason = _clip_reason(reason)
|
||||
node.last_checked_at = _now()
|
||||
node.assigns = 0
|
||||
_evict_node(node.id)
|
||||
db.commit()
|
||||
with _lock:
|
||||
_holds.pop(key, None)
|
||||
|
||||
|
||||
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] = []
|
||||
dead_ids: list[int] = []
|
||||
seen_at = _now()
|
||||
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,
|
||||
last_seen_at=seen_at,
|
||||
)
|
||||
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
|
||||
node.last_seen_at = seen_at
|
||||
if node.status == STATUS_DEAD:
|
||||
dead_ids.append(node.id)
|
||||
continue
|
||||
if node.status == STATUS_NEW:
|
||||
new_ids.append(node.id)
|
||||
elif node.status == STATUS_ALIVE:
|
||||
alive_ids.append(node.id)
|
||||
stale_before = seen_at - timedelta(days=7)
|
||||
held = set(_holds.values())
|
||||
for node in list(existing.values()):
|
||||
if node.id in held or node.status != STATUS_DEAD:
|
||||
continue
|
||||
seen = _aware(node.last_seen_at)
|
||||
if seen is not None and seen < stale_before:
|
||||
db.delete(node)
|
||||
existing.pop((node.scheme, node.host, int(node.port)), None)
|
||||
for node in existing.values():
|
||||
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)
|
||||
elif node.status == STATUS_NEW:
|
||||
new_ids.append(node.id)
|
||||
db.commit()
|
||||
probe_ids = _pick_probe_ids(db, new_ids, alive_ids, dead_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)
|
||||
probed = len(results)
|
||||
failed = sum(1 for _node_id, ok, _latency, _reason in results if not ok)
|
||||
if probed >= 3 and failed == probed and not _direct_reaches_target():
|
||||
results = []
|
||||
elif probed < 3:
|
||||
results = [row for row in results if row[1]]
|
||||
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
|
||||
_apply_probe(node, ok, latency, reason)
|
||||
sync.checked_at = _now()
|
||||
sync.running = False
|
||||
db.flush()
|
||||
_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 _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]:
|
||||
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] = []
|
||||
seen: set[int] = set()
|
||||
|
||||
def add(node_id: int) -> None:
|
||||
if node_id in seen or len(ordered) >= MAX_PROBES:
|
||||
return
|
||||
seen.add(node_id)
|
||||
ordered.append(node_id)
|
||||
|
||||
for node in new_nodes:
|
||||
if len(ordered) >= new_budget:
|
||||
break
|
||||
add(node.id)
|
||||
for node in alive_nodes:
|
||||
if len(ordered) >= MAX_PROBES:
|
||||
break
|
||||
add(node.id)
|
||||
for node in new_nodes:
|
||||
if len(ordered) >= MAX_PROBES:
|
||||
break
|
||||
add(node.id)
|
||||
cutoff = _now() - timedelta(minutes=30)
|
||||
for node_id in dead_ids or []:
|
||||
if len(ordered) >= MAX_PROBES or node_id in seen:
|
||||
continue
|
||||
node = db.get(ProxyNode, node_id)
|
||||
checked = _aware(node.last_checked_at) if node is not None else None
|
||||
if checked is None or checked > cutoff:
|
||||
continue
|
||||
add(node_id)
|
||||
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]] = []
|
||||
pool = ThreadPoolExecutor(max_workers=workers)
|
||||
try:
|
||||
futures = {
|
||||
pool.submit(probe, scheme, host, port): node_id
|
||||
for node_id, scheme, host, port in nodes
|
||||
}
|
||||
try:
|
||||
for future in as_completed(futures, timeout=PROBE_BATCH_TIMEOUT):
|
||||
node_id = futures[future]
|
||||
try:
|
||||
ok, latency, reason = future.result()
|
||||
except Exception as exc:
|
||||
ok, latency, reason = False, 0, _short_reason(exc)
|
||||
results.append((node_id, ok, latency, reason))
|
||||
except TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
pool.shutdown(wait=False, cancel_futures=True)
|
||||
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 = _clip_reason(reason)
|
||||
node.assigns = 0
|
||||
_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 request_probe(ids: list[int] | None = None) -> dict:
|
||||
"""整表探测放到后台,避免一次请求卡住到超时。"""
|
||||
with _probe_guard:
|
||||
if _probe_state["running"]:
|
||||
return {"running": True, "count": _probe_state["count"], "items": []}
|
||||
_probe_state["running"] = True
|
||||
_probe_state["error"] = ""
|
||||
_probe_state["count"] = 0
|
||||
|
||||
def work() -> None:
|
||||
try:
|
||||
result = probe_ids(ids)
|
||||
with _probe_guard:
|
||||
_probe_state["count"] = int(result.get("count") or 0)
|
||||
_probe_state["error"] = ""
|
||||
except Exception as exc:
|
||||
log.warning("代理探测失败:%s", exc, exc_info=True)
|
||||
with _probe_guard:
|
||||
text = str(exc).strip() or "探测失败"
|
||||
_probe_state["error"] = text[:200]
|
||||
finally:
|
||||
with _probe_guard:
|
||||
_probe_state["running"] = False
|
||||
|
||||
threading.Thread(target=work, name="euniv-proxy-probe", daemon=True).start()
|
||||
return {"running": True, "count": 0, "items": []}
|
||||
|
||||
|
||||
def probe_state() -> dict:
|
||||
with _probe_guard:
|
||||
return {
|
||||
"running": _probe_state["running"],
|
||||
"count": _probe_state["count"],
|
||||
"error": _probe_state["error"],
|
||||
}
|
||||
|
||||
|
||||
def probe_ids(ids: list[int] | None = None) -> dict:
|
||||
if ids is not None and not ids:
|
||||
return {"ok": True, "count": 0, "items": []}
|
||||
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)
|
||||
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 _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:
|
||||
_reset_pool_running()
|
||||
stop = threading.Event()
|
||||
|
||||
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
|
||||
def retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool:
|
||||
"""请求已经失败。放掉当前代理,让下一次重新领取。"""
|
||||
mark_failed(employee_id, proxy_url, reason)
|
||||
return True
|
||||
|
||||
Reference in New Issue
Block a user