Rotate the proxy on every route failure and make the live timeout configurable
CI / Python 3.13 (push) Successful in 36s
CI / Python 3.12 (push) Successful in 45s
CI / Build and smoke-test image (push) Successful in 12s

This commit is contained in:
omar committed 2026-11-29 07:32:44 +03:00
1 parent 4f5180a8f8
commit 710b2e068c
12 files changed
+116 -50

No files matched your search

+2
View File
@@ -9,4 +9,6 @@ MCP_PROXY_URLS=[]
MCP_PROXY_LIST_REFRESH_MINUTES=15
# Keep the last N entries of the returned list and rotate them round-robin.
MCP_PROXY_LIST_LIMIT=100
# Per-attempt ceiling for a live page, proxy connect included. Search budget = value + 0.5.
MCP_LIVE_TIMEOUT_SECONDS=9.5
MCP_HTTP_MAX_RETRIES=3
+1
View File
@@ -67,6 +67,7 @@ The second command waits for MCP messages on stdin. In an MCP host, use `uv` as
| `MCP_PROXY_LIST_TOKEN` | Bearer token used only for fetching the proxy list. Use HTTPS or a trusted isolated network: HTTP does not encrypt the token. |
| `MCP_PROXY_LIST_REFRESH_MINUTES` | Refresh interval, an integer from 0 to 1440; default 15. Zero means fetch only at startup. |
| `MCP_PROXY_LIST_LIMIT` | How many trailing entries of the fetched list to keep, an integer from 1 to 1024; default 100. The kept proxies are used round-robin. |
| `MCP_LIVE_TIMEOUT_SECONDS` | Ceiling for one live attempt, from 1 to 60; default 9.5. It covers the proxy connection as well. A search waits this long plus 0.5 s for rendering. |
| `MCP_HTTP_MAX_RETRIES` | Retries after the initial attempt, from 0 to 8; default 3. Changing proxies does not reset the budget. |
For a proxy list provider, set the URL and token and leave `MCP_PROXY_URLS` unset or `[]`. An example URL is `https://proxy-service.example/v1/proxies?proxy_type=http&format=proxy-url-list-txt`. Docker supports a private `--env-file`. Lists are capped at 1 MiB of text; blank lines are ignored, the last `MCP_PROXY_LIST_LIMIT` entries are kept and used round-robin. Several accounts on one gateway are distinct routes even though they share a host and port. An empty or invalid response preserves the previous pool. If there has been no successful refresh, the local index remains available but live requests cannot use a direct fallback.
+5
View File
@@ -20,6 +20,7 @@ class Settings:
proxy_list_token: str | None = field(default=None, repr=False)
proxy_list_refresh_minutes: int = 15
proxy_list_limit: int = 100
live_timeout: float = 9.5
@classmethod
def load(cls) -> "Settings":
@@ -45,6 +46,9 @@ class Settings:
limit = values.get("MCP_PROXY_LIST_LIMIT", "100")
if not limit or not re.fullmatch(r"[0-9]{1,4}", limit) or not 1 <= int(limit) <= 1024:
raise ValueError("MCP_PROXY_LIST_LIMIT must be an integer from 1 to 1024")
timeout = values.get("MCP_LIVE_TIMEOUT_SECONDS", "9.5")
if not timeout or not re.fullmatch(r"[0-9]{1,2}(?:\.[0-9])?", timeout) or not 1 <= float(timeout) <= 60:
raise ValueError("MCP_LIVE_TIMEOUT_SECONDS must be a number from 1 to 60")
proxies = _proxies(values.get("MCP_PROXY_URLS", "[]"))
endpoint = values.get("MCP_PROXY_LIST_URL")
token = values.get("MCP_PROXY_LIST_TOKEN")
@@ -68,6 +72,7 @@ class Settings:
proxy_list_token=token,
proxy_list_refresh_minutes=int(minutes),
proxy_list_limit=int(limit),
live_timeout=float(timeout),
live_route=live_route,
)
+2 -2
View File
@@ -984,7 +984,7 @@ class Search:
return token
async def search(self, query: str, asset: AssetFacts | None = None, cursor: str | None = None) -> SearchPage:
deadline = monotonic() + 9.5
deadline = monotonic() + self._http.budget
asset_key = _asset_key(asset)
request = _query(query, asset)
binding = (_identity(request), asset_key)
@@ -1107,7 +1107,7 @@ class Search:
)
async def get_advisory(self, id: str) -> AdvisoryResult:
deadline = monotonic() + 9.5
deadline = monotonic() + self._http.budget
ident = _id(_validated(id, 200, 'id'))
if not (_NATIVE.fullmatch(ident) or _OSV.fullmatch(ident) or _CATALOG_ID.fullmatch(ident)):
raise ValueError('invalid_id')
+41 -24
View File
@@ -26,6 +26,8 @@ _CHUNK = 256 * 1024
_JSON_LIMIT = 32 * 1024**2
_DOWNLOAD_LIMIT = 256 * 1024**2
_LIVE_SECONDS = 9.5
# Kept back from the live deadline so a hit page is rendered, not just fetched.
_RESULT_RESERVE = 0.5
_BULK_SECONDS = 3600
_MAX_TIMESTAMP = 253402300799.0
_REDIRECTS = {301, 302, 303, 307, 308}
@@ -505,9 +507,14 @@ async def _read_body(response: httpx.Response, limit: int, path: Path | None) ->
class _Sender:
def __init__(self, gate: _PublisherGate, max_retries: int) -> None:
def __init__(self, gate: _PublisherGate, max_retries: int, live_timeout: float = _LIVE_SECONDS) -> None:
self.gate = gate
self.max_retries = max_retries
# One value bounds a whole attempt, the proxy connection included.
self.live_timeout = live_timeout
def _timeout(self, live: bool) -> httpx.Timeout:
return httpx.Timeout(self.live_timeout) if live else httpx.Timeout(60, connect=3)
async def request(
self,
@@ -610,7 +617,7 @@ class _Sender:
trace = _Trace(route.proxy)
request = route.client.build_request(
method, url, json=body, headers=headers,
timeout=httpx.Timeout(9.5 if live else 60, connect=3), extensions={"trace": trace},
timeout=self._timeout(live), extensions={"trace": trace},
)
# Explicit Request suppresses replay from HTTPX's response cookie jar.
request.headers.pop("Cookie", None)
@@ -628,42 +635,46 @@ class _Sender:
rate_limited = await self.gate.rate_limit(source, route.label, code, response.headers, url.host)
if rate_limited is not None:
raise _Retry(rate_limited)
if code in {401, 403}:
raise HttpError("access_denied")
if code == 407:
# The proxy itself rejected the account: only a settings change helps.
route.unhealthy_until = math.inf
raise _Retry(HttpError("proxy_unavailable"))
if code == 404:
raise HttpError("not_found")
if code in {502, 503, 504}:
# Everything else may be one bad egress IP, so the next attempt
# draws the next proxy; the status still reports what happened.
if code == 403:
raise _Retry(HttpError("access_denied"), backoff=True)
if code in {408, 500, 502, 503, 504, 505}:
raise _Retry(HttpError("unavailable"), backoff=True)
raise HttpError("invalid_data" if code == 400 else "unavailable")
if code == 400:
raise HttpError("invalid_data")
raise _Retry(HttpError("unavailable"), backoff=True)
finally:
await response.aclose()
except httpx.HTTPError as exc:
# A transport error is an egress-route accident until proven otherwise:
# retry on the next proxy and only keep the status for the final report.
if isinstance(exc, httpx.ProxyError) and trace.proxy_auth_failed:
route.unhealthy_until = math.inf
raise HttpError("proxy_unavailable") from None
raise _Retry(HttpError("proxy_unavailable")) from None
if isinstance(exc, httpx.ConnectError) and trace.proxy_tcp_failed:
route.unhealthy_until = monotonic() + 30
raise _Retry(HttpError("proxy_unavailable")) from None
if isinstance(exc, httpx.ReadTimeout):
raise _Retry(HttpError("timeout"), backoff=True) from None
if isinstance(exc, httpx.ConnectTimeout):
if not live:
raise _Retry(HttpError("timeout"), backoff=True) from None
raise HttpError("timeout") from None
if isinstance(exc, httpx.TimeoutException):
raise HttpError("timeout") from None
if isinstance(exc, httpx.ConnectError) and not live:
if isinstance(exc, httpx.DecodingError):
# A truncated or mangled body is the payload's problem, not the route's.
raise HttpError("invalid_data") from None
if isinstance(exc, httpx.ConnectError):
cause: BaseException | None = exc
while cause is not None:
if isinstance(cause, ssl.SSLError):
# Certificate verdicts are identical on every IP.
raise HttpError("unavailable") from None
cause = cause.__cause__
raise _Retry(HttpError("unavailable"), backoff=True) from None
if not live and isinstance(exc, (httpx.ReadError, httpx.WriteError, httpx.RemoteProtocolError)):
raise _Retry(HttpError("unavailable"), backoff=True) from None
if isinstance(exc, httpx.DecodingError):
raise HttpError("invalid_data") from None
raise HttpError("unavailable") from None
if isinstance(exc, httpx.TimeoutException):
raise _Retry(HttpError("timeout"), backoff=True) from None
raise _Retry(HttpError("unavailable"), backoff=True) from None
def _deadline(value: float | None, seconds: float) -> float:
@@ -710,9 +721,15 @@ class LiveHttp:
def __init__(self, sender: _Sender, routing: _Route | _ProxyPool) -> None:
self._sender = sender
self._routing = routing
self.timeout = sender.live_timeout
self._cache: OrderedDict[tuple[str, str, str], _Cached] = OrderedDict()
self._cache_size = 0
@property
def budget(self) -> float:
"""A caller deadline that lets the request finish and still render a page."""
return self.timeout + _RESULT_RESERVE
def _remove(self, key: tuple[str, str, str]) -> None:
old = self._cache.pop(key, None)
if old is not None:
@@ -728,7 +745,7 @@ class LiveHttp:
async def bytes(self, source: str, url: str, *, deadline: float, limit: int) -> tuple[bytes, httpx.Headers]:
result = await self._sender.request(
source, _allowed(source, url, live=True, method="GET"), self._routing, live=True, body=None,
headers=_headers(None, "*/*"), deadline=_deadline(deadline, _LIVE_SECONDS),
headers=_headers(None, "*/*"), deadline=_deadline(deadline, self._sender.live_timeout),
limit=min(limit, _JSON_LIMIT), allow_304=False,
)
if result.body is None:
@@ -741,7 +758,7 @@ class LiveHttp:
headers: Mapping[str, str] | None = None, budget: float | None = None,
) -> tuple[Any, httpx.Headers]:
# A background refresh of a large artefact needs more than the per-search cap.
deadline = monotonic() + budget if budget is not None else _deadline(deadline, _LIVE_SECONDS)
deadline = monotonic() + budget if budget is not None else _deadline(deadline, self._sender.live_timeout)
method = "POST" if body is not None else "GET"
requested = _parsed_url(source, url, True, method, params)
outbound = _headers(headers, "application/json")
@@ -842,7 +859,7 @@ class HttpClients:
opening.push_async_callback(routing.replace, ())
await routing.replace(self._settings.proxies)
self._stack = opening.pop_all()
sender = _Sender(_PublisherGate(self._store), self._settings.max_retries)
sender = _Sender(_PublisherGate(self._store), self._settings.max_retries, self._settings.live_timeout)
self.live = LiveHttp(sender, routing)
self.index = IndexHttp(sender, _Route("direct", direct))
return self
+10
View File
@@ -106,3 +106,13 @@ def test_proxy_list_limit_bounds(monkeypatch):
else:
with pytest.raises(ValueError):
Settings.load()
def test_live_timeout_is_configurable_and_bounded(monkeypatch, tmp_path):
monkeypatch.setenv('MCP_LIVE_TIMEOUT_SECONDS', '4.5')
assert Settings.load().live_timeout == 4.5
assert Settings(tmp_path).live_timeout == 9.5
for value in ('0.5', '61', 'nope', ''):
monkeypatch.setenv('MCP_LIVE_TIMEOUT_SECONDS', value)
with pytest.raises(ValueError):
Settings.load()
+1 -1
View File
@@ -125,7 +125,7 @@ async def test_schneider_catalog_refresh_and_live_revalidation(tmp_path, monkeyp
return original_client(transport=httpx.MockTransport(respond), trust_env=False)
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy")
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
sync = Sync(store, clients.index)
assert await sync.refresh_once("industrial")
+1 -1
View File
@@ -82,7 +82,7 @@ async def test_public_cve_and_adv_publish_and_revalidate(tmp_path, monkeypatch)
return original_client(transport=httpx.MockTransport(respond), trust_env=False)
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy")
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
assert await Sync(store, clients.index).refresh_once("msrc")
[cve] = await store.by_id(_CVE)
+1 -1
View File
@@ -102,7 +102,7 @@ async def test_redhat_live_revalidates_each_call_and_preserves_branch_scope(vex,
return client(transport=httpx.MockTransport(send), trust_env=False)
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy")
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
first = await lookup("redhat", "id", _CVE.lower(), http=clients.live, deadline=monotonic() + 5)
second = await lookup("redhat", "id", _CVE, http=clients.live, deadline=monotonic() + 5)
+5
View File
@@ -106,6 +106,11 @@ class PublisherHTTP:
'path': '/modules/exploits/fixture/module.rb', 'references': ['CVE-2025-0001'], 'rank': 300,
}}
self.templates: set[str] = set()
self.timeout = 9.5
@property
def budget(self) -> float:
return self.timeout + 0.5
async def json(self, source: str, url: str, *, params=None, body=None, deadline=None, headers=None,
budget=None):
+44 -18
View File
@@ -73,7 +73,7 @@ def clock(monkeypatch: pytest.MonkeyPatch) -> Clock:
def settings(
proxies: tuple[str, ...] = PROXIES, retries: int = 0, *, live_route: Literal["direct", "proxy"] = "proxy",
) -> SimpleNamespace:
return SimpleNamespace(proxies=proxies, max_retries=retries, live_route=live_route)
return SimpleNamespace(proxies=proxies, max_retries=retries, live_route=live_route, live_timeout=9.5)
def routed_clients(
@@ -194,8 +194,8 @@ async def test_only_a_proven_proxy_tcp_error_rotates_immediately(monkeypatch, st
@pytest.mark.anyio
@pytest.mark.parametrize("failure", [httpx.ProxyError, httpx.ConnectError, 403, 404])
async def test_ambiguous_proxy_failure_does_not_retry_or_disable(monkeypatch, store, failure):
@pytest.mark.parametrize("failure", [httpx.ProxyError, httpx.ConnectError, 403, 408, 500, 502, 504])
async def test_a_route_failure_moves_to_the_next_proxy(monkeypatch, store, failure):
seen = []
async def respond(route, request):
@@ -208,13 +208,14 @@ async def test_ambiguous_proxy_failure_does_not_retry_or_disable(monkeypatch, st
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=3), store) as clients:
expected = {403: "access_denied", 404: "not_found"}.get(failure, "unavailable")
error = await status(clients.live.json("siemens", SIEMENS), expected)
assert "credential-like" not in "".join(traceback.format_exception(error))
assert seen == ["proxy-a.test"]
value, _headers = await clients.live.json("siemens", SIEMENS)
assert value == {}
await clients.live.json("siemens", SIEMENS)
await clients.live.json("siemens", SIEMENS)
assert seen == ["proxy-a.test", "proxy-b.test", "proxy-a.test"]
# The failed attempt moved on, and an unproven failure did not disable the route.
assert seen[:2] == ["proxy-a.test", "proxy-b.test"]
assert "proxy-a.test" in seen[2:]
assert all(route in {httpx.URL(url).host for url in PROXIES} for route in seen)
@pytest.mark.anyio
@@ -249,8 +250,8 @@ async def test_explicit_direct_live_isolated_and_revalidates(monkeypatch, store,
async def respond(route, request):
seen.append((route, str(request.url), request.headers.get("If-None-Match")))
limits = request.extensions["timeout"]
assert limits["connect"] == 3
assert limits["read"] == (9.5 if route == "live-direct" else 60)
assert limits["connect"] == (9.5 if route == "live-direct" else 3)
match len(seen):
case 1:
trace = request.extensions["trace"]
@@ -275,7 +276,7 @@ async def test_explicit_direct_live_isolated_and_revalidates(monkeypatch, store,
await status(clients.live.json("kev", KEV), "invalid_data")
await status(clients.index.json("nvd", NVD), "invalid_data")
await status(clients.live.json("epss", EPSS, deadline=clock.mono), "timeout")
await status(clients.live.json("siemens", SIEMENS), "unavailable")
await status(clients.live.json("siemens", SIEMENS), "timeout")
assert (await clients.live.json("siemens", SIEMENS))[0] == {"channel": "live"}
assert (await clients.index.json("siemens", SIEMENS))[0] == {"channel": "index"}
assert (await clients.live.json("siemens", SIEMENS))[0] == {"channel": "live"}
@@ -723,19 +724,22 @@ async def test_real_connect_credentials_tls_cookie_isolation_and_confirmed_407(m
await clients.index.json("siemens", SIEMENS, headers={"Cookie": "user=secret", "Proxy-Authorization": "forged"})
await clients.live.json("siemens", SIEMENS)
await clients.live.json("siemens", SIEMENS)
async with HttpClients(settings((f"http://user:forbidden-secret@127.0.0.1:{reject}", proxies[1])), store) as clients:
error = await status(clients.live.json("siemens", SIEMENS), "proxy_unavailable")
assert str(error) == "proxy_unavailable"
retired = (f"http://user:forbidden-secret@127.0.0.1:{reject}", proxies[1])
async with HttpClients(settings(retired, retries=1), store) as clients:
# A confirmed 407 retires that route and the call moves to the next proxy.
await clients.live.json("siemens", SIEMENS)
await clients.live.json("siemens", SIEMENS)
assert [label for label, _ in proxy_headers] == ["A", "B", "A", "reject", "B", "B"]
await clients.live.json("siemens", SIEMENS)
assert [label for label, _ in proxy_headers] == ["A", "B", "A", "reject", "B", "B", "B"]
assert proxy_headers[:2] == [
("A", b"Basic " + base64.b64encode(b"alice:p@ss:A")),
("B", b"Basic " + base64.b64encode(b"bob:s3cret B")),
]
assert len(upstream) == 6
assert len(upstream) == 7
assert all(b"proxy-authorization" not in headers and b"cookie" not in headers for headers in upstream)
assert [headers.get(b"if-none-match") for headers in upstream] == [None, None, b'"origin-1"', b'"origin-1"', None, b'"origin-1"']
assert [headers.get(b"if-none-match") for headers in upstream] == [
None, None, b'"origin-1"', b'"origin-1"', None, b'"origin-1"', b'"origin-1"',
]
assert all(secret not in caplog.text for secret in ("forbidden-secret", "p@ss:A", "s3cret B", "user=secret"))
@@ -773,9 +777,14 @@ async def test_real_https_proxy_verifies_both_tls_hops(store, loopback_ca, certi
if certificate == "valid":
assert (await clients.live.json("siemens", SIEMENS))[0] == {}
else:
# A certificate verdict is the same on every egress IP: no rotation.
await status(clients.live.json("siemens", SIEMENS), "unavailable")
if certificate in {"valid", "wrong-origin-name"}:
assert proxy_headers == [("TLS", b"Basic " + base64.b64encode(b"alice:p@ss"))]
credentials = ("TLS", b"Basic " + base64.b64encode(b"alice:p@ss"))
if certificate == "wrong-origin-name":
# The tunnel came up, so the origin certificate failure was retried once.
assert proxy_headers == [credentials, credentials]
elif certificate == "valid":
assert proxy_headers == [credentials]
else:
assert proxy_headers == []
if certificate == "valid":
@@ -829,3 +838,20 @@ async def test_real_socks_resolves_origin_at_proxy_and_sends_decoded_credentials
assert journal == [(b"alice@example.test", b"p:ss word", b"cert-portal.siemens.com", 443)]
assert len(upstream) == 1
assert b"proxy-authorization" not in upstream[0] and b"authorization" not in upstream[0]
@pytest.mark.anyio
async def test_configured_timeout_bounds_the_attempt_including_the_proxy_connect(monkeypatch, store):
seen = {}
async def respond(route, request):
seen.update(request.extensions["timeout"])
return httpx.Response(200, json={})
routed_clients(monkeypatch, respond)
tuning = settings(retries=0)
tuning.live_timeout = 4.5
async with HttpClients(tuning, store) as clients:
assert clients.live.budget == 5.0
await clients.live.json("siemens", SIEMENS)
assert {seen["connect"], seen["read"], seen["write"], seen["pool"]} == {4.5}
+3 -3
View File
@@ -88,7 +88,7 @@ async def test_apache_refresh_preserves_published_generation_on_bad_catalog(tmp_
return client(transport=httpx.MockTransport(respond))
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=(), max_retries=0, live_route="proxy")
settings = SimpleNamespace(proxies=(), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
sync = Sync(store, clients.index)
assert await sync.refresh_once("web")
@@ -138,7 +138,7 @@ async def test_apache_detail_revalidates_through_proxy(tmp_path: Path, monkeypat
return client(transport=httpx.MockTransport(respond))
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy")
settings = SimpleNamespace(proxies=("http://proxy.test:8080",), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
first = await lookup_web("id", "cve-2024-38475", http=clients.live, deadline=monotonic() + 5)
second = await lookup_web("id", _MODERN, http=clients.live, deadline=monotonic() + 5)
@@ -180,7 +180,7 @@ async def test_apache_search_filters_fixes_to_legacy_branch(tmp_path: Path, monk
return client(transport=httpx.MockTransport(respond))
monkeypatch.setattr(httpx, "AsyncClient", make_client)
settings = SimpleNamespace(proxies=(), max_retries=0, live_route="proxy")
settings = SimpleNamespace(proxies=(), max_retries=0, live_route="proxy", live_timeout=9.5)
async with Store(tmp_path) as store, HttpClients(settings, store) as clients:
assert await Sync(store, clients.index).refresh_once("web")
search = Search(store, clients.live)