Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion httpx/_decoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ def decode(self, data: bytes) -> bytes:
self.seen_data = True
output = io.BytesIO()
try:
# zstd decompressors cannot be reused after EOF, so start a new one
# when more data arrives after a completed frame. This is done lazily
# so that `flush()` can check whether the current frame is complete.
if data and self.decompressor.eof:
self.decompressor = zstandard.ZstdDecompressor().decompressobj()
output.write(self.decompressor.decompress(data))
while self.decompressor.eof and self.decompressor.unused_data:
unused_data = self.decompressor.unused_data
Expand All @@ -196,7 +201,7 @@ def flush(self) -> bytes:
return b""
ret = self.decompressor.flush() # note: this is a no-op
if not self.decompressor.eof:
raise DecodingError("Zstandard data is incomplete") # pragma: no cover
raise DecodingError("Zstandard data is incomplete")
return bytes(ret)


Expand Down
48 changes: 48 additions & 0 deletions tests/test_decoders.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,54 @@ def test_zstd_multiframe():
assert response.content == b"foobar"


def test_zstd_streaming_multiple_frames():
body1 = b"test 123 "
body2 = b"another frame"

# Create two separate complete frames
frame1 = zstd.compress(body1)
frame2 = zstd.compress(body2)

# Create an iterator that yields frames separately
def content_iterator() -> typing.Iterator[bytes]:
yield frame1
yield frame2

headers = [(b"Content-Encoding", b"zstd")]
response = httpx.Response(200, headers=headers, content=content_iterator())
response.read()

assert response.content == body1 + body2


def test_zstd_streaming_truncated_second_frame():
frame1 = zstd.compress(b"first")
frame2 = zstd.compress(b"second")

def content_iterator() -> typing.Iterator[bytes]:
yield frame1
yield frame2[:12]

headers = [(b"Content-Encoding", b"zstd")]
response = httpx.Response(200, headers=headers, content=content_iterator())
with pytest.raises(httpx.DecodingError):
response.read()


def test_zstd_streaming_empty_chunk_after_frame():
frame = zstd.compress(b"complete")

def content_iterator() -> typing.Iterator[bytes]:
yield frame
yield b""

headers = [(b"Content-Encoding", b"zstd")]
response = httpx.Response(200, headers=headers, content=content_iterator())
response.read()

assert response.content == b"complete"


def test_multi():
body = b"test 123"

Expand Down
Loading