Skip to content
This repository was archived by the owner on Jun 5, 2025. It is now read-only.

Commit 19186fd

Browse files
authored
Generate valid chunked response when returning short circuit answer (#1001)
Prior to this change, this code would return a malformed HTTP response with a chunk size, then HTTP header, then body, then the final chunk size, final chunk then zero. This changes the code to return the header before returning the code. Furthermore, it does not count the size of the header in the first chunk size.
1 parent 4bf4a5f commit 19186fd

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

src/codegate/providers/copilot/provider.py

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -111,19 +111,29 @@ class HttpResponse:
111111
headers: List[str]
112112
body: Optional[bytes] = None
113113

114-
def reconstruct(self) -> bytes:
115-
"""Reconstruct HTTP response from stored details"""
114+
def reconstruct_headers(self) -> bytes:
115+
"""
116+
Reconstruct the HTTP header of the response.
117+
"""
116118
headers = "\r\n".join(self.headers)
117119
status_line = f"{self.version} {self.status_code} {self.reason}\r\n"
118120
header_block = f"{status_line}{headers}\r\n\r\n"
121+
return header_block.encode("utf-8")
119122

120-
# Convert header block to bytes and combine with body
121-
result = header_block.encode("utf-8")
123+
def reconstruct_body(self) -> bytes:
124+
"""
125+
Reconstruct the body of the response.
126+
"""
127+
result = b""
122128
if self.body:
123129
result += self.body
124-
130+
result += b"\n\n"
125131
return result
126132

133+
def reconstruct(self) -> bytes:
134+
"""Reconstruct HTTP response from stored details"""
135+
return self.reconstruct_headers() + self.reconstruct_body()
136+
127137

128138
def extract_path(full_path: str) -> str:
129139
"""Extract clean path from full URL or path string"""
@@ -387,8 +397,12 @@ async def _forward_data_to_target(self, data: bytes) -> None:
387397
# request to the target
388398
self.target_transport.close()
389399

390-
# Send the shortcut response data in a chunk
391-
chunk = pipeline_output.reconstruct()
400+
# Send the HTTP headers
401+
# Note that this representation ends with \r\n\r\n
402+
self.transport.write(pipeline_output.reconstruct_headers())
403+
404+
# Encode the body, send its length, then the data
405+
chunk = pipeline_output.reconstruct_body()
392406
chunk_size = hex(len(chunk))[2:] + "\r\n"
393407
self.transport.write(chunk_size.encode())
394408
self.transport.write(chunk)

0 commit comments

Comments
 (0)