Live reads go through an operator proxy pool (round-robin over the newest 100 entries, cooling on connect failures, no direct fallback); stored clearances are replayed only on the exit that earned them. Identity, clearance, solver and Turnstile rungs escalate automatically. fetch_pages reads up to 12 URLs four at a time with per-item isolation. report/reports/reports_update keep a durable queue of unreadable pages for the operator. Ships a pinned multi-stage image (non-root 10001, data in /data), an ordered CI with static gates, tests on 3.12 and 3.13 at 85% coverage, an offline image smoke, and sha/latest publishing gated on main.
340 lines
12 KiB
Python
340 lines
12 KiB
Python
"""Operator-managed proxy pool: exclusive sources, atomic refresh, round-robin.
|
|
|
|
Configuration is read once from the environment; the agent never chooses a
|
|
route. Two exclusive sources exist: a literal JSON array (``MCP_PROXY_URLS``)
|
|
or an HTTP list service (``MCP_PROXY_LIST_URL`` + ``MCP_PROXY_LIST_TOKEN``).
|
|
The list service is always read directly, never through the pool, and its
|
|
token goes nowhere else.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
from collections.abc import Iterator
|
|
from dataclasses import dataclass, field
|
|
from datetime import UTC, datetime
|
|
from email.utils import parsedate_to_datetime
|
|
from ipaddress import IPv4Address, IPv6Address, ip_address
|
|
from threading import Event, Lock, Thread
|
|
from time import monotonic
|
|
from urllib.parse import quote, unquote, urlsplit
|
|
|
|
_SCHEMES = frozenset({"http", "https", "socks5", "socks5h"})
|
|
_DEFAULT_PORTS = {"http": 80, "https": 443, "socks5": 1080, "socks5h": 1080}
|
|
_BAD = re.compile(r"[\x00-\x20\x7f\\]")
|
|
_AUTHORITY = re.compile(r"(?:([^:@/\[\]]+):([^@/]*)@)?(\[[0-9a-fA-F:.]+\]|[^:@/\[\]]+)(?::([0-9]{1,5}))?\Z")
|
|
_MAX_LIST_BODY = 1024 * 1024
|
|
_MAX_PROXIES = 512
|
|
|
|
|
|
class PoolError(ValueError):
|
|
"""The pool configuration or the list service is unusable."""
|
|
|
|
|
|
@dataclass(frozen=True, slots=True, eq=False)
|
|
class Proxy:
|
|
"""One pool entry. Identity is the URL, so a refresh keeps surviving objects."""
|
|
|
|
url: str
|
|
scheme: str
|
|
host: str
|
|
port: int
|
|
user: str = ""
|
|
password: str = ""
|
|
|
|
@property
|
|
def label(self) -> str:
|
|
"""URL with the password masked, safe for messages and logs."""
|
|
userinfo = f"{quote(self.user, safe='')}:***@" if self.user else ""
|
|
host = f"[{self.host}]" if ":" in self.host else self.host
|
|
return f"{self.scheme}://{userinfo}{host}:{self.port}"
|
|
|
|
|
|
def _parse(raw: str) -> Proxy:
|
|
url = raw.strip()
|
|
if not url or len(url) > 2048 or _BAD.search(url) or "#" in url or "?" in url:
|
|
raise PoolError(f"invalid proxy URL: {raw.strip()!r}")
|
|
try:
|
|
parts = urlsplit(url)
|
|
except ValueError:
|
|
raise PoolError(f"invalid proxy URL: {raw.strip()!r}") from None
|
|
scheme = parts.scheme.lower()
|
|
if scheme not in _SCHEMES:
|
|
raise PoolError(f"unsupported proxy scheme {parts.scheme!r}")
|
|
if parts.path not in {"", "/"}:
|
|
raise PoolError(f"proxy URL must have no path: {raw.strip()!r}")
|
|
match = _AUTHORITY.fullmatch(parts.netloc)
|
|
if match is None:
|
|
raise PoolError(f"invalid proxy authority: {raw.strip()!r}")
|
|
user, password, host, port_text = match.groups()
|
|
if (user is None) != (password is None):
|
|
raise PoolError("proxy credentials need both user and password")
|
|
port = int(port_text) if port_text else _DEFAULT_PORTS[scheme]
|
|
if not 1 <= port <= 65535:
|
|
raise PoolError("proxy port must be in 1..65535")
|
|
user, password = unquote(user or ""), unquote(password or "")
|
|
if host.startswith("["):
|
|
host = host[1:-1]
|
|
try:
|
|
ip_address(host)
|
|
except ValueError:
|
|
if host.startswith("[") or ":" in host:
|
|
raise PoolError(f"invalid proxy IP literal: {host!r}") from None
|
|
host = host.lower()
|
|
canonical_host = f"[{host}]" if ":" in host else host
|
|
userinfo = f"{quote(user, safe='')}:{quote(password, safe='')}@" if user else ""
|
|
canonical = f"{scheme}://{userinfo}{canonical_host}:{port}"
|
|
return Proxy(canonical, scheme, host, port, user or "", password or "")
|
|
|
|
|
|
def parse_one(raw: str) -> Proxy:
|
|
"""Public single-URL parser for a pinned proxy."""
|
|
return _parse(raw)
|
|
|
|
|
|
def parse_list(text: str) -> tuple[Proxy, ...]:
|
|
"""Parse a whole one-URL-per-line list, rejecting it as a unit."""
|
|
seen: dict[str, Proxy] = {}
|
|
for _number, line in enumerate(text.splitlines(), 1):
|
|
if not line.strip():
|
|
continue
|
|
if len(seen) >= _MAX_PROXIES:
|
|
raise PoolError(f"more than {_MAX_PROXIES} proxies")
|
|
proxy = _parse(line)
|
|
seen.setdefault(proxy.url, proxy)
|
|
if not seen:
|
|
raise PoolError("proxy list is empty")
|
|
return tuple(seen.values())
|
|
|
|
|
|
def retry_after_seconds(value: str | None, now: datetime | None = None) -> float | None:
|
|
"""Delay from a Retry-After header (delta-seconds or HTTP-date), or None."""
|
|
if not value:
|
|
return None
|
|
value = value.strip()
|
|
if value.isdigit():
|
|
return float(value)
|
|
try:
|
|
moment = parsedate_to_datetime(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
if moment.tzinfo is None:
|
|
moment = moment.replace(tzinfo=UTC)
|
|
return max(0.0, (moment - (now or datetime.now(UTC))).total_seconds())
|
|
|
|
|
|
@dataclass
|
|
class _Entry:
|
|
proxy: Proxy
|
|
cooling_until: float = 0.0
|
|
last_error: str = ""
|
|
in_flight: int = 0
|
|
|
|
|
|
@dataclass
|
|
class Pool:
|
|
"""Available proxies in fixed order, plus per-proxy cooldown state."""
|
|
|
|
refresh_minutes: int = 15
|
|
limit: int = 100
|
|
entries: list[_Entry] = field(default_factory=list)
|
|
_cursor: int = 0
|
|
_lock: Lock = field(default_factory=Lock)
|
|
_route: str = "proxy"
|
|
_list_url: str = ""
|
|
_token: str = ""
|
|
_version: int = 0
|
|
_stop: Event = field(default_factory=Event)
|
|
_thread: Thread | None = None
|
|
_last_refresh: float = 0.0
|
|
_last_error: str = ""
|
|
|
|
@property
|
|
def route(self) -> str:
|
|
return self._route
|
|
|
|
@property
|
|
def version(self) -> int:
|
|
return self._version
|
|
|
|
def __len__(self) -> int:
|
|
with self._lock:
|
|
return len(self.entries)
|
|
|
|
def snapshot(self) -> list[dict[str, object]]:
|
|
with self._lock:
|
|
now = monotonic()
|
|
return [
|
|
{
|
|
"proxy": entry.proxy.label,
|
|
"available": entry.cooling_until <= now,
|
|
"in_flight": entry.in_flight,
|
|
"last_error": entry.last_error,
|
|
}
|
|
for entry in self.entries
|
|
]
|
|
|
|
def acquire(self, pinned: str | None = None) -> _Entry | None:
|
|
"""Next proxy in rotation that is not cooling; None when none is usable.
|
|
|
|
A ``pinned`` URL is preferred, which keeps a clearance on its own exit IP.
|
|
"""
|
|
with self._lock:
|
|
now = monotonic()
|
|
if pinned:
|
|
for entry in self.entries:
|
|
if pinned in {entry.proxy.url, entry.proxy.label} and entry.cooling_until <= now:
|
|
entry.in_flight += 1
|
|
return entry
|
|
count = len(self.entries)
|
|
for offset in range(count):
|
|
index = (self._cursor + offset) % count
|
|
entry = self.entries[index]
|
|
if entry.cooling_until <= now:
|
|
entry.in_flight += 1
|
|
self._cursor = (index + 1) % count
|
|
return entry
|
|
return None
|
|
|
|
def release(self, entry: _Entry) -> None:
|
|
with self._lock:
|
|
entry.in_flight = max(0, entry.in_flight - 1)
|
|
|
|
def cool(self, entry: _Entry, seconds: float, reason: str) -> None:
|
|
with self._lock:
|
|
entry.cooling_until = monotonic() + seconds
|
|
entry.last_error = reason
|
|
|
|
def _apply(self, proxies: tuple[Proxy, ...]) -> None:
|
|
with self._lock:
|
|
current = {entry.proxy.url: entry for entry in self.entries}
|
|
self.entries = [current.get(proxy.url) or _Entry(proxy) for proxy in proxies]
|
|
self._version += 1
|
|
for entry in self.entries:
|
|
entry.last_error = ""
|
|
|
|
def load_literal(self, raw: str) -> None:
|
|
try:
|
|
values = json.loads(raw)
|
|
except json.JSONDecodeError as error:
|
|
raise PoolError(f"MCP_PROXY_URLS is not valid JSON: {error}") from None
|
|
if not isinstance(values, list) or not all(isinstance(value, str) for value in values):
|
|
raise PoolError("MCP_PROXY_URLS must be a JSON array of strings")
|
|
if len(values) > _MAX_PROXIES:
|
|
raise PoolError(f"more than {_MAX_PROXIES} proxies")
|
|
seen: dict[str, Proxy] = {}
|
|
for value in values:
|
|
if value.strip():
|
|
proxy = _parse(value)
|
|
seen.setdefault(proxy.url, proxy)
|
|
if not seen:
|
|
raise PoolError("MCP_PROXY_URLS contains no proxy")
|
|
self._apply(tuple(seen.values())[-self.limit :])
|
|
|
|
def refresh(self, fetch) -> bool:
|
|
"""Replace the pool from the list service; keep the last good list on error."""
|
|
try:
|
|
text = fetch(self._list_url, self._token)
|
|
proxies = parse_list(text)
|
|
except ValueError as error: # PoolError and transport.FetchError alike.
|
|
with self._lock:
|
|
self._last_error = str(error)
|
|
return False
|
|
self._apply(proxies[-self.limit :])
|
|
with self._lock:
|
|
self._last_error = ""
|
|
self._last_refresh = monotonic()
|
|
return True
|
|
|
|
def start(self, fetch) -> bool:
|
|
"""First load happens synchronously; later refreshes run in the background."""
|
|
if self._route != "proxy" or not self._list_url:
|
|
return False
|
|
loaded = self.refresh(fetch)
|
|
if self.refresh_minutes <= 0:
|
|
return loaded
|
|
|
|
def loop() -> None:
|
|
while not self._stop.wait(self.refresh_minutes * 60):
|
|
self.refresh(fetch)
|
|
|
|
self._thread = Thread(target=loop, name="proxy-refresh", daemon=True)
|
|
self._thread.start()
|
|
return loaded
|
|
|
|
def stop(self) -> None:
|
|
self._stop.set()
|
|
|
|
def iter_entries(self) -> Iterator[_Entry]:
|
|
with self._lock:
|
|
yield from list(self.entries)
|
|
|
|
|
|
def from_env(environ: dict[str, str] | None = None) -> Pool:
|
|
"""Build a pool from operator settings, validating mutually exclusive sources."""
|
|
env = os.environ if environ is None else environ
|
|
route = (env.get("MCP_LIVE_ROUTE") or "proxy").strip().lower()
|
|
if route not in {"proxy", "direct"}:
|
|
raise PoolError("MCP_LIVE_ROUTE must be proxy or direct")
|
|
pool = Pool(_route=route)
|
|
if route == "direct":
|
|
return pool
|
|
|
|
urls = (env.get("MCP_PROXY_URLS") or "").strip()
|
|
list_url = (env.get("MCP_PROXY_LIST_URL") or "").strip()
|
|
token = (env.get("MCP_PROXY_LIST_TOKEN") or "").strip()
|
|
if urls and list_url:
|
|
raise PoolError("set either MCP_PROXY_URLS or MCP_PROXY_LIST_URL, not both")
|
|
if not urls and not list_url:
|
|
raise PoolError("MCP_LIVE_ROUTE=proxy needs MCP_PROXY_URLS or MCP_PROXY_LIST_URL")
|
|
if list_url and not token:
|
|
raise PoolError("MCP_PROXY_LIST_URL needs MCP_PROXY_LIST_TOKEN")
|
|
if urls:
|
|
pool.load_literal(urls)
|
|
return pool
|
|
|
|
pool._list_url = list_url
|
|
pool._token = token
|
|
pool.limit = _limit(env)
|
|
refresh = (env.get("MCP_PROXY_LIST_REFRESH_MINUTES") or "15").strip()
|
|
try:
|
|
pool.refresh_minutes = int(refresh)
|
|
except ValueError:
|
|
raise PoolError("MCP_PROXY_LIST_REFRESH_MINUTES must be an integer") from None
|
|
if pool.refresh_minutes < 0:
|
|
raise PoolError("MCP_PROXY_LIST_REFRESH_MINUTES must be >= 0")
|
|
return pool
|
|
|
|
|
|
def _limit(env: dict[str, str]) -> int:
|
|
raw = (env.get("MCP_PROXY_LIMIT") or "100").strip()
|
|
try:
|
|
value = int(raw)
|
|
except ValueError:
|
|
raise PoolError("MCP_PROXY_LIMIT must be an integer") from None
|
|
if not 1 <= value <= _MAX_PROXIES:
|
|
raise PoolError(f"MCP_PROXY_LIMIT must be in 1..{_MAX_PROXIES}")
|
|
return value
|
|
|
|
|
|
def max_retries(environ: dict[str, str] | None = None) -> int:
|
|
env = os.environ if environ is None else environ
|
|
raw = (env.get("MCP_HTTP_MAX_RETRIES") or "3").strip()
|
|
try:
|
|
value = int(raw)
|
|
except ValueError:
|
|
raise PoolError("MCP_HTTP_MAX_RETRIES must be an integer") from None
|
|
if not 0 <= value <= 9:
|
|
raise PoolError("MCP_HTTP_MAX_RETRIES must be in 0..9")
|
|
return value
|
|
|
|
|
|
def is_private_host(host: str) -> bool:
|
|
try:
|
|
address = ip_address(host)
|
|
except ValueError:
|
|
return False
|
|
if isinstance(address, (IPv4Address, IPv6Address)):
|
|
return not address.is_global
|
|
return False
|