Spaces:
Running
Running
File size: 3,645 Bytes
a821b6f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | """Fixed-upstream HTTP forwarding for the public FastAPI entry point."""
import logging
from http.cookiejar import DefaultCookiePolicy
import httpx
from fastapi import Request
from fastapi.responses import JSONResponse, StreamingResponse
from starlette.background import BackgroundTask
logger = logging.getLogger("uvicorn.error")
MAX_BODY_BYTES = 25 * 1024 * 1024
HOP_HEADERS = {
b"connection", b"keep-alive", b"proxy-authenticate", b"proxy-authorization",
b"te", b"trailer", b"trailers", b"transfer-encoding", b"upgrade",
}
def forward_headers(headers, *, request=False):
excluded = HOP_HEADERS.copy()
if request:
excluded.update({b"host", b"x-forwarded-host", b"x-forwarded-proto"})
for name, value in headers:
if name.lower() == b"connection":
excluded.update(token.strip().lower() for token in value.split(b","))
return [(name, value) for name, value in headers if name.lower() not in excluded]
class BodyTooLarge(Exception):
pass
class NoUpstreamCookies(DefaultCookiePolicy):
"""A shared connection pool must never share browser sessions."""
def set_ok(self, cookie, request):
return False
async def proxy_request(request: Request, base_url: str, timeout: float | None):
length = request.headers.get("content-length")
if length:
try:
if int(length) < 0:
return JSONResponse({"detail": "Invalid Content-Length"}, status_code=400)
if int(length) > MAX_BODY_BYTES:
return JSONResponse({"detail": "Request body exceeds 25 MiB"}, status_code=413)
except ValueError:
return JSONResponse({"detail": "Invalid Content-Length"}, status_code=400)
async def body():
size = 0
async for chunk in request.stream():
size += len(chunk)
if size > MAX_BODY_BYTES:
raise BodyTooLarge()
yield chunk
base = httpx.URL(base_url)
raw_path = request.scope.get("raw_path", request.url.path.encode("utf-8"))
query = request.scope.get("query_string", b"")
target = base.copy_with(raw_path=base.raw_path.rstrip(b"/") + raw_path + (b"?" + query if query else b""))
headers = forward_headers(request.headers.raw, request=True)
headers.append((b"x-forwarded-host", request.headers.get("host", "").encode("latin-1")))
headers.append((b"x-forwarded-proto", request.headers.get("x-forwarded-proto", request.url.scheme).encode("latin-1")))
client = request.app.state.proxy_client
try:
upstream = await client.send(client.build_request(
request.method, target, headers=headers, content=body(), timeout=timeout,
), stream=True)
except BodyTooLarge:
return JSONResponse({"detail": "Request body exceeds 25 MiB"}, status_code=413)
except httpx.TimeoutException:
return JSONResponse({"detail": "Upstream response timed out"}, status_code=504)
except httpx.RequestError as error:
logger.warning("Gateway upstream failure: %s", type(error).__name__)
return JSONResponse({"detail": "Upstream service unavailable"}, status_code=502)
async def response_body():
try:
# Preserve encoded bytes and stream SSE without buffering.
async for chunk in upstream.aiter_raw():
yield chunk
finally:
await upstream.aclose()
response = StreamingResponse(response_body(), status_code=upstream.status_code,
background=BackgroundTask(upstream.aclose))
response.raw_headers = forward_headers(upstream.headers.raw)
return response
|