Merge pull request #458 from chenyme/enhance_proxy

feat: Enhance proxy management with improved failure handling and clearance refresh logic
This commit is contained in:
Chenyme authored and GitHub committed 2026-04-12 17:17:37 +08:00
commit e2c20d9c40
11 files changed
+159 -52

No files matched your search

+69 -4
View File
@@ -39,6 +39,9 @@ class ProxyDirectory:
self._flare = FlareSolverrClearanceProvider()
self._egress_mode: EgressMode = EgressMode.DIRECT
self._clearance_mode: ClearanceMode = ClearanceMode.NONE
# Pool cursor for PROXY_POOL mode: sticky routing with failure-driven rotate.
# Incremented on node failure; all callers see the same cursor under _lock.
self._pool_cursor: int = 0
# ------------------------------------------------------------------
# Lifecycle
@@ -127,6 +130,26 @@ class ProxyDirectory:
update={"state": ClearanceBundleState.INVALID}
)
# In PROXY_POOL mode, rotate to the next node on any failure so the
# next acquire() prefers a different egress rather than hammering the
# same broken node.
if (
self._egress_mode == EgressMode.PROXY_POOL
and lease.proxy_url
and result.kind in (
ProxyFeedbackKind.CHALLENGE,
ProxyFeedbackKind.UNAUTHORIZED,
ProxyFeedbackKind.FORBIDDEN,
ProxyFeedbackKind.TRANSPORT_ERROR,
)
):
async with self._lock:
self._pool_cursor += 1
logger.debug(
"proxy pool cursor advanced: proxy={} kind={} cursor={}",
lease.proxy_url, result.kind, self._pool_cursor,
)
# ------------------------------------------------------------------
# Internal
# ------------------------------------------------------------------
@@ -142,8 +165,9 @@ class ProxyDirectory:
return None
if self._egress_mode == EgressMode.SINGLE_PROXY:
return nodes[0].proxy_url
# PROXY_POOL: pick least-inflight node.
return min(nodes, key=lambda n: n.inflight).proxy_url
# PROXY_POOL: sticky routing — use current cursor, rotate on failure.
idx = self._pool_cursor % len(nodes)
return nodes[idx].proxy_url
async def _get_or_build_bundle(
self,
@@ -208,8 +232,8 @@ class ProxyDirectory:
async def warm_up(self) -> None:
"""Pre-fetch clearance bundles for all configured affinity keys.
Called once at startup and after each scheduled invalidation so that
the first real request does not have to wait for FlareSolverr.
Called once at startup so the first real request does not have to wait
for FlareSolverr. Does NOT invalidate existing bundles first.
"""
if self._clearance_mode == ClearanceMode.NONE:
return
@@ -226,6 +250,47 @@ class ProxyDirectory:
proxy_url = proxy_url,
)
async def refresh_clearance_safe(self) -> None:
"""Scheduled clearance refresh: build new bundles then swap atomically.
Unlike ``invalidate_clearance() + warm_up()``, this never discards a
working bundle before a replacement is ready. If FlareSolverr is
temporarily unavailable the old bundle remains valid and continues to
serve requests.
"""
if self._clearance_mode == ClearanceMode.NONE:
return
async with self._lock:
nodes = list(self._nodes)
existing = set(self._bundles.keys())
affinity_items = (
[(n.proxy_url or "direct", n.proxy_url or "") for n in nodes]
if nodes
else [("direct", "")]
)
# Also refresh bundles for keys that no longer have a matching node
# (e.g. pool was reconfigured) so stale entries get cleaned up.
all_keys = {a for a, _ in affinity_items} | existing
for affinity in all_keys:
proxy_url = "" if affinity == "direct" else affinity
if self._clearance_mode == ClearanceMode.MANUAL:
new_bundle = self._manual.build_bundle(affinity_key=affinity)
else:
new_bundle = await self._flare.refresh_bundle(
affinity_key = affinity,
proxy_url = proxy_url,
)
if new_bundle:
async with self._lock:
self._bundles[affinity] = new_bundle
logger.debug("clearance bundle refreshed: affinity={}", affinity)
else:
logger.warning(
"clearance refresh failed, keeping old bundle: affinity={}", affinity
)
# ------------------------------------------------------------------
# Properties
# ------------------------------------------------------------------
+6 -3
View File
@@ -61,10 +61,13 @@ class ProxyClearanceScheduler:
logger.warning("proxy clearance warm-up failed: error={}", exc)
async def _refresh(self) -> None:
"""Invalidate cached clearance bundles and pre-fetch fresh ones."""
"""Build fresh clearance bundles and swap atomically (build-then-swap).
Old bundles are kept if FlareSolverr is unavailable, so a transient
refresh failure never leaves requests without clearance.
"""
try:
await self._directory.invalidate_clearance()
await self._directory.warm_up()
await self._directory.refresh_clearance_safe()
logger.debug("proxy clearance refresh completed")
except Exception as exc:
logger.warning("proxy clearance refresh failed: error={}", exc)
+12 -7
View File
@@ -160,14 +160,19 @@ def _client_hints(browser: Optional[str], ua: Optional[str]) -> dict[str, str]:
def _resolve_profile(lease: ProxyLease | None) -> tuple[str, str]:
"""Return (cf_cookies, user_agent) from lease or config."""
if lease is not None:
return (lease.cf_cookies or "", lease.user_agent or "")
"""Return (cf_cookies, user_agent) from lease or config.
Field-level fallback: if the lease exists but a field is empty (e.g. no
clearance bundle yet), the config default is used rather than returning an
empty string. This prevents bare requests with no User-Agent when running
in direct mode or when FlareSolverr has not yet delivered a bundle.
"""
cfg = get_config()
return (
cfg.get_str("proxy.clearance.cf_cookies", ""),
cfg.get_str("proxy.clearance.user_agent", ""),
)
cfg_cookies = cfg.get_str("proxy.clearance.cf_cookies", "")
cfg_ua = cfg.get_str("proxy.clearance.user_agent", "")
if lease is not None:
return (lease.cf_cookies or cfg_cookies, lease.user_agent or cfg_ua)
return (cfg_cookies, cfg_ua)
def _resolve_browser(lease: ProxyLease | None) -> str:
@@ -0,0 +1,35 @@
"""Shared helper: map an UpstreamError to the correct ProxyFeedbackKind.
All transport modules (assets, media, livekit, imagine_ws …) use this so the
mapping stays consistent and clearance bundles are properly invalidated.
Rules
-----
401 → UNAUTHORIZED (invalidates clearance bundle)
403 → CHALLENGE (invalidates clearance bundle — treat all 403s as potential CF)
429 → RATE_LIMITED
≥500 → UPSTREAM_5XX
else → TRANSPORT_ERROR
"""
from app.platform.errors import UpstreamError
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind
def upstream_feedback(exc: UpstreamError) -> ProxyFeedback:
"""Return a ``ProxyFeedback`` for an ``UpstreamError`` response."""
status = exc.status or 0
if status == 401:
kind = ProxyFeedbackKind.UNAUTHORIZED
elif status == 403:
kind = ProxyFeedbackKind.CHALLENGE
elif status == 429:
kind = ProxyFeedbackKind.RATE_LIMITED
elif status >= 500:
kind = ProxyFeedbackKind.UPSTREAM_5XX
else:
kind = ProxyFeedbackKind.TRANSPORT_ERROR
return ProxyFeedback(kind=kind, status_code=status or None)
__all__ = ["upstream_feedback"]
@@ -192,6 +192,14 @@ async def upload_from_input(token: str, file_input: str) -> tuple[str, str]:
resp = await session.get(file_input, headers=headers, timeout=30.0)
raw = resp.content
if resp.status_code != 200:
await proxy.feedback(
lease,
ProxyFeedback(
kind = ProxyFeedbackKind.UPSTREAM_5XX if resp.status_code >= 500
else ProxyFeedbackKind.FORBIDDEN,
status_code = resp.status_code,
),
)
raise UpstreamError(
f"Failed to fetch input URL: {resp.status_code}",
status = resp.status_code,
@@ -200,9 +208,13 @@ async def upload_from_input(token: str, file_input: str) -> tuple[str, str]:
or "application/octet-stream")
filename = file_input.split("/")[-1].split("?")[0] or "download"
b64 = base64.b64encode(raw).decode()
finally:
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS))
except UpstreamError:
raise
except Exception as exc:
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
raise UpstreamError(f"Asset fetch transport error: {exc}") from exc
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS))
return await upload_file(token, filename, mime, b64)
# Data URI
+4 -15
View File
@@ -30,6 +30,7 @@ def _get_delete_sem() -> asyncio.Semaphore:
return _delete_sem
from app.platform.errors import UpstreamError
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind
from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback
from app.dataplane.proxy import get_proxy_runtime
from app.dataplane.reverse.protocol.xai_assets import (
ASSETS_LIST_URL,
@@ -85,11 +86,7 @@ async def _list_assets_inner(
except UpstreamError as exc:
await proxy.feedback(
lease,
ProxyFeedback(
kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
else ProxyFeedbackKind.FORBIDDEN,
status_code = exc.status or 502,
),
upstream_feedback(exc),
)
raise
except Exception as exc:
@@ -135,11 +132,7 @@ async def _delete_asset_inner(token: str, asset_id: str) -> dict:
except UpstreamError as exc:
await proxy.feedback(
lease,
ProxyFeedback(
kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
else ProxyFeedbackKind.FORBIDDEN,
status_code = exc.status or 502,
),
upstream_feedback(exc),
)
raise
except Exception as exc:
@@ -208,11 +201,7 @@ async def download_asset(
except UpstreamError as exc:
await proxy.feedback(
lease,
ProxyFeedback(
kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
else ProxyFeedbackKind.FORBIDDEN,
status_code = exc.status or 502,
),
upstream_feedback(exc),
)
raise
except Exception as exc:
+11 -1
View File
@@ -22,8 +22,9 @@ import orjson
from app.platform.logging.logger import logger
from app.platform.config.snapshot import get_config
from app.control.proxy.models import ProxyScope, RequestKind
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind
from app.dataplane.proxy import get_proxy_runtime
from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback
from app.dataplane.proxy.adapters.headers import build_ws_headers
from app.dataplane.reverse.protocol.xai_image import (
WS_IMAGINE_URL,
@@ -319,6 +320,10 @@ async def stream_images(
except Exception as exc:
status = getattr(exc, "status", None)
logger.error("imagine websocket connect failed: error={}", exc)
from app.platform.errors import UpstreamError as _UE
fb = upstream_feedback(_UE("connect failed", status=status)) \
if status else ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR)
await proxy.feedback(lease, fb)
yield {
"type": "error",
"error_code": "rate_limit_exceeded" if status == 429 else "connection_failed",
@@ -348,6 +353,7 @@ async def stream_images(
collected += 1
yield ev
if ev["type"] == "error":
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
return
else:
# _stream_round exhausted without a _meta — shouldn't happen
@@ -358,13 +364,17 @@ async def stream_images(
except aiohttp.ClientError as exc:
logger.error("imagine websocket connection failed: error={}", exc)
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
yield {"type": "error", "error_code": "connection_failed", "error": str(exc)}
return
if collected >= n:
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200))
return
# Server closed the connection but we still need more images → reconnect.
# Give back the current lease before acquiring a new one on the next iteration.
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200))
logger.info("imagine websocket reconnecting: remaining_images={} requested_images={}", n - collected, n)
+4 -13
View File
@@ -22,6 +22,7 @@ from app.dataplane.reverse.protocol.xai_livekit import (
)
from app.dataplane.reverse.transport.http import post_json
from app.dataplane.reverse.transport.websocket import WebSocketClient, WebSocketConnection
from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback
# ------------------------------------------------------------------
@@ -63,20 +64,10 @@ async def fetch_livekit_token(
referer = "https://grok.com/",
)
except UpstreamError as exc:
await proxy.feedback(
lease,
ProxyFeedback(
kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
else ProxyFeedbackKind.FORBIDDEN,
status_code = exc.status or 502,
),
)
await proxy.feedback(lease, upstream_feedback(exc))
raise
except Exception as exc:
await proxy.feedback(
lease,
ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR),
)
await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
raise UpstreamError(f"fetch_livekit_token: transport error: {exc}") from exc
await proxy.feedback(
@@ -114,7 +105,7 @@ async def connect_livekit_ws(
timeout = timeout_s if timeout_s is not None else cfg.get_float("voice.timeout", 120.0)
proxy = await get_proxy_runtime()
lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.WS)
lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.WEBSOCKET)
url = build_ws_url(access_token)
headers = build_ws_headers(token=token, lease=lease)
+2 -5
View File
@@ -9,6 +9,7 @@ from app.platform.logging.logger import logger
from app.platform.config.snapshot import get_config
from app.platform.errors import UpstreamError
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind
from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback
from app.dataplane.proxy import get_proxy_runtime
from app.dataplane.reverse.protocol.xai_video import (
MEDIA_LINK_URL,
@@ -50,11 +51,7 @@ async def _post_with_proxy(
except UpstreamError as exc:
await proxy.feedback(
lease,
ProxyFeedback(
kind = ProxyFeedbackKind.UPSTREAM_5XX if (exc.status or 0) >= 500
else ProxyFeedbackKind.FORBIDDEN,
status_code = exc.status or 502,
),
upstream_feedback(exc),
)
raise
except Exception as exc:
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "grok2api"
version = "2.0.4.rc0"
version = "2.0.4.rc1"
description = "Grok2API rebuilt with FastAPI, fully aligned with the latest web call format. Supports streaming and non-streaming chat, image generation/editing, deep thinking, token pool concurrency, and automatic load balancing."
readme = "README.md"
requires-python = ">=3.13"
Generated
+1 -1
View File
@@ -580,7 +580,7 @@ wheels = [
[[package]]
name = "grok2api"
version = "2.0.4rc0"
version = "2.0.4rc1"
source = { virtual = "." }
dependencies = [
{ name = "aiohttp" },