Skip to content

Commit f5f1139

Browse files
committed
Raise error on truncated and optimize for prebuffered
Signed-off-by: Anuraag Agrawal <anuraaga@gmail.com>
1 parent 2b0e1cb commit f5f1139

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/connectrpc/_server_sync.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,16 +118,28 @@ def prepare_response_headers(
118118
def _read_body_with_content_length(
119119
environ: WSGIEnvironment, content_length: int
120120
) -> bytes:
121-
bytes_read = 0
122-
chunks = []
123121
input_stream: BytesIO = environ["wsgi.input"]
122+
123+
# Many app servers buffer the entire request before executing the app
124+
# so do an optimistic read before looping.
125+
chunk = input_stream.read(content_length)
126+
if len(chunk) == content_length:
127+
return chunk
128+
129+
bytes_read = len(chunk)
130+
chunks = [chunk]
124131
while bytes_read < content_length:
125132
to_read = content_length - bytes_read
126133
chunk = input_stream.read(to_read)
127134
if not chunk:
128135
break
129136
chunks.append(chunk)
130137
bytes_read += len(chunk)
138+
if bytes_read < content_length:
139+
raise ConnectError(
140+
Code.INVALID_ARGUMENT,
141+
f"request truncated, expected {content_length} bytes but only received {bytes_read} bytes",
142+
)
131143
return b"".join(chunks)
132144

133145

0 commit comments

Comments
 (0)