Skip to content

Commit

Permalink
fix: always stream response
Browse files Browse the repository at this point in the history
  • Loading branch information
NarekA committed Dec 6, 2023
1 parent 676ca4c commit ac1febe
Showing 1 changed file with 18 additions and 31 deletions.
49 changes: 18 additions & 31 deletions jina/serve/runtimes/gateway/request_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
import json
from typing import TYPE_CHECKING, AsyncIterator, Dict

from aiohttp.client import _RequestContextManager

from jina.enums import ProtocolType
from jina.helper import get_full_version
from jina.proto import jina_pb2
Expand Down Expand Up @@ -159,11 +157,7 @@ async def _load_balance(self, request):

try:
async with aiohttp.ClientSession() as session:

request_kwargs = {
'headers': request.headers,
'params': request.query,
}
request_kwargs = {}
try:
payload = await request.read()
if payload:
Expand All @@ -172,34 +166,27 @@ async def _load_balance(self, request):
self.logger.debug('No JSON payload found in request')

Check warning on line 166 in jina/serve/runtimes/gateway/request_handling.py

View check run for this annotation

Codecov / codecov/patch

jina/serve/runtimes/gateway/request_handling.py#L165-L166

Added lines #L165 - L166 were not covered by tests

async with session.request(
request.method, target_url, **request_kwargs
request.method,
url=target_url,
headers=request.headers,
**request_kwargs,
) as response:
# Looking for application/octet-stream, text/event-stream, text/stream
if response.content_type.endswith('stream'):

# Create a StreamResponse with the same headers and status as the target response
stream_response = web.StreamResponse(
status=response.status,
headers=response.headers,
)

# Prepare the response to send headers
await stream_response.prepare(request)

# Stream the response from the target server to the client
async for chunk in response.content.iter_any():
await stream_response.write(chunk)

# Close the stream response once all chunks are sent
await stream_response.write_eof()
return stream_response
content = await response.read()
return web.Response(
body=content,
# Create a StreamResponse with the same headers and status as the target response
stream_response = web.StreamResponse(
status=response.status,
content_type=response.content_type,
headers=response.headers,
)

# Prepare the response to send headers
await stream_response.prepare(request)

# Stream the response from the target server to the client
async for chunk in response.content.iter_any():
await stream_response.write(chunk)

# Close the stream response once all chunks are sent
await stream_response.write_eof()
return stream_response
except aiohttp.ClientError as e:
return web.Response(text=f'Error: {str(e)}', status=500)

Expand Down

0 comments on commit ac1febe

Please sign in to comment.