Skip to content

Commit 88de4ae

Browse files
committed
Fix #38: enable streaming proxy with async chunk iteration
Pass stream=True to requests.request in signed_call.py so the response body is not buffered before being returned. Replace iter_content() in call_backend.py with an async generator that reads 8192-byte chunks and offloads each blocking socket read to a thread via asyncio.to_thread, eliminating ~28s of unnecessary latency.
1 parent 20724be commit 88de4ae

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

shard_core/service/signed_call.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ async def signed_request(
1515
*args, identity: Identity = None, **kwargs
1616
) -> requests.Response:
1717
auth = get_signature_auth(identity)
18-
response = await asyncio.to_thread(requests.request, *args, auth=auth, **kwargs)
18+
response = await asyncio.to_thread(
19+
requests.request, *args, auth=auth, stream=True, **kwargs
20+
)
1921
return response
2022

2123

shard_core/web/internal/call_backend.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
import logging
23
from fastapi import APIRouter, Request
34

@@ -12,6 +13,15 @@
1213
router = APIRouter()
1314

1415

16+
async def async_iter_content(response, chunk_size=8192):
17+
iterator = response.iter_content(chunk_size=chunk_size)
18+
while True:
19+
chunk = await asyncio.to_thread(next, iterator, None)
20+
if chunk is None:
21+
break
22+
yield chunk
23+
24+
1525
@router.api_route("/call_backend/{rest:path}", methods=ALL_HTTP_METHODS)
1626
async def call_backend(rest: str, request: Request):
1727
base_url = gconf.get("freeshard_controller.base_url")
@@ -27,5 +37,5 @@ async def call_backend(rest: str, request: Request):
2737
return StreamingResponse(
2838
status_code=response.status_code,
2939
headers=response.headers,
30-
content=response.iter_content(),
40+
content=async_iter_content(response, chunk_size=8192),
3141
)

0 commit comments

Comments
 (0)