-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop_backend_proxy.py
More file actions
93 lines (80 loc) · 2.52 KB
/
Copy pathloop_backend_proxy.py
File metadata and controls
93 lines (80 loc) · 2.52 KB
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
90
91
92
93
"""Proxy loop-backend routes using LOOP_BACKEND_URL (preview-safe)."""
from __future__ import annotations
import os
from typing import Mapping
import urllib3
from fastapi import HTTPException, Request
from starlette.responses import Response
_HOP_BY_HOP = frozenset(
{
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
"host",
"content-length",
}
)
_REQUEST_HEADER_DENYLIST = _HOP_BY_HOP | {"accept-encoding"}
_RESPONSE_HEADER_DENYLIST = _HOP_BY_HOP | {"content-encoding"}
_POOL = urllib3.PoolManager()
def _loop_backend_base() -> str:
base = os.environ.get("LOOP_BACKEND_URL", "").strip().rstrip("/")
if not base:
raise HTTPException(
status_code=503,
detail="Loop backend is not configured for this deployment.",
)
return base
def _forward_headers(request: Request) -> dict[str, str]:
headers: dict[str, str] = {}
for key, value in request.headers.items():
lowered = key.lower()
if lowered in _REQUEST_HEADER_DENYLIST:
continue
headers[key] = value
return headers
def _response_headers(upstream: Mapping[str, str]) -> dict[str, str]:
return {
key: value
for key, value in upstream.items()
if key.lower() not in _RESPONSE_HEADER_DENYLIST
}
async def proxy_loop_backend(request: Request, upstream_path: str) -> Response:
base = _loop_backend_base()
query = f"?{request.url.query}" if request.url.query else ""
url = f"{base}{upstream_path}{query}"
body = await request.body()
try:
upstream = _POOL.request(
request.method,
url,
body=body or None,
headers=_forward_headers(request),
redirect=False,
preload_content=False,
)
except urllib3.exceptions.HTTPError as err:
raise HTTPException(
status_code=502,
detail="Loop backend request failed.",
) from err
try:
payload = upstream.read()
except urllib3.exceptions.HTTPError as err:
raise HTTPException(
status_code=502,
detail="Loop backend response read failed.",
) from err
finally:
upstream.release_conn()
return Response(
content=payload,
status_code=upstream.status,
headers=_response_headers(upstream.headers),
media_type=upstream.headers.get("content-type"),
)