Spaces:
Running
Running
Deploy 4d7b00d5
Browse files
backend/integrations/cloudflare_transport.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Choose a reachable Cloudflare IPv4 route while retaining TLS verification."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import asyncio
|
| 5 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 6 |
+
import socket
|
| 7 |
+
import ssl
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import httpx
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
HOST = "api.cloudflare.com"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ReachableCloudflareRoutes:
|
| 18 |
+
"""Resolve normally and cache only addresses with a verified TLS handshake."""
|
| 19 |
+
|
| 20 |
+
def __init__(self):
|
| 21 |
+
self._lock = threading.Lock()
|
| 22 |
+
self._routes = []
|
| 23 |
+
self._expires = 0.0
|
| 24 |
+
|
| 25 |
+
@staticmethod
|
| 26 |
+
def _probe(address):
|
| 27 |
+
try:
|
| 28 |
+
with socket.create_connection((address, 443), timeout=3) as conn:
|
| 29 |
+
with ssl.create_default_context().wrap_socket(conn, server_hostname=HOST):
|
| 30 |
+
return address
|
| 31 |
+
except OSError:
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
def select(self, excluded=()):
|
| 35 |
+
with self._lock:
|
| 36 |
+
now = time.monotonic()
|
| 37 |
+
routes = [item for item in self._routes if item not in excluded] if now < self._expires else []
|
| 38 |
+
if routes:
|
| 39 |
+
return routes[0]
|
| 40 |
+
addresses = list(dict.fromkeys(item[4][0] for item in socket.getaddrinfo(HOST, 443, socket.AF_INET, socket.SOCK_STREAM)))[:12]
|
| 41 |
+
addresses = [item for item in addresses if item not in excluded]
|
| 42 |
+
with ThreadPoolExecutor(max_workers=max(1, len(addresses))) as pool:
|
| 43 |
+
futures = [pool.submit(self._probe, address) for address in addresses]
|
| 44 |
+
routes = [route for future in as_completed(futures) if (route := future.result())]
|
| 45 |
+
self._routes = routes
|
| 46 |
+
self._expires = time.monotonic() + 60
|
| 47 |
+
if not routes:
|
| 48 |
+
raise httpx.ConnectError("No verified Cloudflare IPv4 route was reachable")
|
| 49 |
+
return routes[0]
|
| 50 |
+
|
| 51 |
+
def invalidate(self, address):
|
| 52 |
+
with self._lock:
|
| 53 |
+
self._routes = [route for route in self._routes if route != address]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _routed_request(request, address):
|
| 57 |
+
if request.url.scheme != "https" or request.url.host != HOST:
|
| 58 |
+
raise ValueError("Cloudflare transport only permits the official HTTPS API host")
|
| 59 |
+
headers = httpx.Headers(request.headers)
|
| 60 |
+
headers["Host"] = HOST
|
| 61 |
+
extensions = dict(request.extensions)
|
| 62 |
+
extensions["sni_hostname"] = HOST
|
| 63 |
+
return httpx.Request(request.method, request.url.copy_with(host=address), headers=headers,
|
| 64 |
+
stream=request.stream, extensions=extensions)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class CloudflareTransport(httpx.BaseTransport):
|
| 68 |
+
def __init__(self, routes):
|
| 69 |
+
self.routes = routes
|
| 70 |
+
self.transport = httpx.HTTPTransport(local_address="0.0.0.0", retries=0)
|
| 71 |
+
|
| 72 |
+
def handle_request(self, request):
|
| 73 |
+
excluded = []
|
| 74 |
+
for attempt in range(3):
|
| 75 |
+
address = self.routes.select(excluded)
|
| 76 |
+
try:
|
| 77 |
+
return self.transport.handle_request(_routed_request(request, address))
|
| 78 |
+
except (httpx.ConnectError, httpx.ConnectTimeout):
|
| 79 |
+
self.routes.invalidate(address)
|
| 80 |
+
excluded.append(address)
|
| 81 |
+
if attempt == 2:
|
| 82 |
+
raise
|
| 83 |
+
|
| 84 |
+
def close(self):
|
| 85 |
+
self.transport.close()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class AsyncCloudflareTransport(httpx.AsyncBaseTransport):
|
| 89 |
+
def __init__(self, routes):
|
| 90 |
+
self.routes = routes
|
| 91 |
+
self.transport = httpx.AsyncHTTPTransport(local_address="0.0.0.0", retries=0)
|
| 92 |
+
|
| 93 |
+
async def handle_async_request(self, request):
|
| 94 |
+
excluded = []
|
| 95 |
+
for attempt in range(3):
|
| 96 |
+
address = await asyncio.to_thread(self.routes.select, excluded)
|
| 97 |
+
try:
|
| 98 |
+
return await self.transport.handle_async_request(_routed_request(request, address))
|
| 99 |
+
except (httpx.ConnectError, httpx.ConnectTimeout):
|
| 100 |
+
await asyncio.to_thread(self.routes.invalidate, address)
|
| 101 |
+
excluded.append(address)
|
| 102 |
+
if attempt == 2:
|
| 103 |
+
raise
|
| 104 |
+
|
| 105 |
+
async def aclose(self):
|
| 106 |
+
await self.transport.aclose()
|
backend/integrations/llm_factory.py
CHANGED
|
@@ -9,6 +9,7 @@ import time
|
|
| 9 |
from collections import deque
|
| 10 |
from typing import Any, Optional
|
| 11 |
from langchain_core.rate_limiters import BaseRateLimiter, InMemoryRateLimiter
|
|
|
|
| 12 |
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
|
@@ -52,6 +53,7 @@ class CloudflareRateLimiter(BaseRateLimiter):
|
|
| 52 |
# Shared by reviewers and evaluation in this process. This request budget is
|
| 53 |
# a conservative application cap, not a measurement of Cloudflare neurons.
|
| 54 |
_cloudflare_limiter = CloudflareRateLimiter(max(1, int(os.getenv("CLOUDFLARE_DAILY_REQUEST_LIMIT", "50"))))
|
|
|
|
| 55 |
DEFAULT_TEMPERATURE = 0.0
|
| 56 |
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 57 |
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
|
@@ -127,8 +129,8 @@ def _get_cloudflare_chat(**kwargs: Any) -> Optional[Any]:
|
|
| 127 |
# Retry only failures while establishing a connection, before an HTTP
|
| 128 |
# request is sent. Preserve normal TLS certificate and hostname checks.
|
| 129 |
# IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
|
| 130 |
-
kwargs.setdefault("http_client", httpx.Client(transport=
|
| 131 |
-
kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=
|
| 132 |
kwargs["timeout"] = timeout
|
| 133 |
kwargs.setdefault("max_retries", 0)
|
| 134 |
kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
|
|
|
|
| 9 |
from collections import deque
|
| 10 |
from typing import Any, Optional
|
| 11 |
from langchain_core.rate_limiters import BaseRateLimiter, InMemoryRateLimiter
|
| 12 |
+
from backend.integrations.cloudflare_transport import CloudflareTransport, AsyncCloudflareTransport, ReachableCloudflareRoutes
|
| 13 |
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
|
|
|
| 53 |
# Shared by reviewers and evaluation in this process. This request budget is
|
| 54 |
# a conservative application cap, not a measurement of Cloudflare neurons.
|
| 55 |
_cloudflare_limiter = CloudflareRateLimiter(max(1, int(os.getenv("CLOUDFLARE_DAILY_REQUEST_LIMIT", "50"))))
|
| 56 |
+
_cloudflare_routes = ReachableCloudflareRoutes()
|
| 57 |
DEFAULT_TEMPERATURE = 0.0
|
| 58 |
DEFAULT_REQUEST_TIMEOUT = float(os.getenv("OCR_MODEL_TIMEOUT_SECONDS", "60"))
|
| 59 |
DEFAULT_OUTPUT_TOKENS = int(os.getenv("OCR_MODEL_MAX_OUTPUT_TOKENS", "2000"))
|
|
|
|
| 129 |
# Retry only failures while establishing a connection, before an HTTP
|
| 130 |
# request is sent. Preserve normal TLS certificate and hostname checks.
|
| 131 |
# IPv6 is unavailable on the hosted Space; keep DNS and TLS SNI intact.
|
| 132 |
+
kwargs.setdefault("http_client", httpx.Client(transport=CloudflareTransport(_cloudflare_routes), timeout=timeout))
|
| 133 |
+
kwargs.setdefault("http_async_client", httpx.AsyncClient(transport=AsyncCloudflareTransport(_cloudflare_routes), timeout=timeout))
|
| 134 |
kwargs["timeout"] = timeout
|
| 135 |
kwargs.setdefault("max_retries", 0)
|
| 136 |
kwargs["max_tokens"] = max(int(kwargs.get("max_tokens") or DEFAULT_OUTPUT_TOKENS), 4096)
|
tests/test_cloudflare_provider.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 1 |
import pytest
|
|
|
|
| 2 |
|
| 3 |
from backend.integrations import llm_factory
|
| 4 |
from eval_data.ragas_eval import ragas_time_limits
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
|
@@ -30,3 +32,36 @@ def test_cloudflare_evaluation_has_room_for_paced_calls(monkeypatch):
|
|
| 30 |
monkeypatch.setenv('OCR_RAGAS_METRIC_TIMEOUT_SECONDS', '12')
|
| 31 |
assert ragas_time_limits('Cloudflare') == (210, 150)
|
| 32 |
assert ragas_time_limits('Gemini') == (30, 12)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import pytest
|
| 2 |
+
import httpx
|
| 3 |
|
| 4 |
from backend.integrations import llm_factory
|
| 5 |
from eval_data.ragas_eval import ragas_time_limits
|
| 6 |
+
from backend.integrations.cloudflare_transport import CloudflareTransport, _routed_request
|
| 7 |
|
| 8 |
|
| 9 |
def test_cloudflare_default_and_shared_pacing(monkeypatch):
|
|
|
|
| 32 |
monkeypatch.setenv('OCR_RAGAS_METRIC_TIMEOUT_SECONDS', '12')
|
| 33 |
assert ragas_time_limits('Cloudflare') == (210, 150)
|
| 34 |
assert ragas_time_limits('Gemini') == (30, 12)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_routing_keeps_host_and_tls_server_name():
|
| 38 |
+
original = httpx.Request('POST', 'https://api.cloudflare.com/client/v4/accounts/test/ai/v1/chat/completions',
|
| 39 |
+
headers={'Authorization': 'Bearer test-key'}, content=b'{}')
|
| 40 |
+
routed = _routed_request(original, '192.0.2.1')
|
| 41 |
+
assert routed.url.host == '192.0.2.1'
|
| 42 |
+
assert routed.headers['Host'] == 'api.cloudflare.com'
|
| 43 |
+
assert routed.extensions['sni_hostname'] == 'api.cloudflare.com'
|
| 44 |
+
assert routed.headers['Authorization'] == 'Bearer test-key'
|
| 45 |
+
with pytest.raises(ValueError):
|
| 46 |
+
_routed_request(httpx.Request('POST', 'https://elsewhere.example/'), '192.0.2.1')
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_transport_tries_another_route_only_for_connect_failure():
|
| 50 |
+
class Routes:
|
| 51 |
+
def __init__(self):
|
| 52 |
+
self.invalidated = []
|
| 53 |
+
def select(self, excluded):
|
| 54 |
+
return '192.0.2.1' if not excluded else '192.0.2.2'
|
| 55 |
+
def invalidate(self, address):
|
| 56 |
+
self.invalidated.append(address)
|
| 57 |
+
routes = Routes()
|
| 58 |
+
transport = CloudflareTransport(routes)
|
| 59 |
+
def respond(request):
|
| 60 |
+
if request.url.host == '192.0.2.1':
|
| 61 |
+
raise httpx.ConnectError('connection failed')
|
| 62 |
+
return httpx.Response(200, json={'ok': True})
|
| 63 |
+
transport.transport = httpx.MockTransport(respond)
|
| 64 |
+
with httpx.Client(transport=transport) as client:
|
| 65 |
+
response = client.post('https://api.cloudflare.com/example', json={})
|
| 66 |
+
assert response.status_code == 200
|
| 67 |
+
assert routes.invalidated == ['192.0.2.1']
|