|
1 |
| -from httpx import AsyncClient |
| 1 | +import httpx |
2 | 2 | from urllib.parse import urlparse
|
3 | 3 |
|
4 | 4 |
|
5 |
| -def asgi_proxy(backend, log=None): |
| 5 | +def asgi_proxy(backend, log=None, timeout=None): |
6 | 6 | backend_host = urlparse(backend).netloc
|
7 | 7 |
|
8 | 8 | async def asgi_proxy(scope, receive, send):
|
@@ -32,7 +32,7 @@ async def asgi_proxy(scope, receive, send):
|
32 | 32 | body += message.get("body", b"")
|
33 | 33 | more_body = message.get("more_body", False)
|
34 | 34 |
|
35 |
| - async with AsyncClient() as client: |
| 35 | + async with httpx.AsyncClient(timeout=timeout) as client: |
36 | 36 | try:
|
37 | 37 | # Stream it, in case of long streaming responses
|
38 | 38 | async with client.stream(
|
@@ -74,10 +74,39 @@ async def asgi_proxy(scope, receive, send):
|
74 | 74 | return
|
75 | 75 |
|
76 | 76 | await send({"type": "http.response.body", "more_body": False})
|
77 |
| - except Exception as e: |
| 77 | + except httpx.TimeoutException as ex: |
| 78 | + if log: |
| 79 | + log.error(f"Timeout error occurred: {ex.__class__.__name__}: {ex}") |
| 80 | + await send( |
| 81 | + { |
| 82 | + "type": "http.response.start", |
| 83 | + "status": 504, |
| 84 | + } |
| 85 | + ) |
| 86 | + await send( |
| 87 | + { |
| 88 | + "type": "http.response.body", |
| 89 | + "body": b"Gateway timeout", |
| 90 | + "more_body": False, |
| 91 | + } |
| 92 | + ) |
| 93 | + except Exception as ex: |
78 | 94 | # Handle any errors during the request
|
79 | 95 | if log:
|
80 |
| - log.error(f"An error occurred: {e.__class__.__name__}: {e}") |
81 |
| - return |
| 96 | + log.error(f"An error occurred: {ex.__class__.__name__}: {ex}") |
| 97 | + await send( |
| 98 | + { |
| 99 | + "type": "http.response.start", |
| 100 | + # Generic gateway error |
| 101 | + "status": 502, |
| 102 | + } |
| 103 | + ) |
| 104 | + await send( |
| 105 | + { |
| 106 | + "type": "http.response.body", |
| 107 | + "body": b"Bad gateway", |
| 108 | + "more_body": False, |
| 109 | + } |
| 110 | + ) |
82 | 111 |
|
83 | 112 | return asgi_proxy
|
0 commit comments