Skip to content
Merged
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
36 changes: 36 additions & 0 deletions src/fishaudio/core/client_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def request(
path: str,
*,
request_options: Optional[RequestOptions] = None,
stream: bool = False,
**kwargs: Any,
) -> httpx.Response:
"""
Expand All @@ -131,6 +132,9 @@ def request(
method: HTTP method (GET, POST, etc.)
path: API endpoint path
request_options: Optional request-level overrides
stream: If True, return as soon as the response headers arrive and
leave the body unread. The caller must consume it with
`iter_bytes()` and then call `close()` on the response.
**kwargs: Additional arguments to pass to httpx.request

Returns:
Expand All @@ -141,6 +145,20 @@ def request(
"""
self._prepare_request_kwargs(request_options, kwargs)

if stream:
timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT)
http_request = self._client.build_request(
method, path, timeout=timeout, **kwargs
)
response = self._client.send(http_request, stream=True)
if not response.is_success:
try:
response.read()
finally:
response.close()
_raise_for_status(response)
return response

# Make the request
response = self._client.request(method, path, **kwargs)

Expand Down Expand Up @@ -194,6 +212,7 @@ async def request(
path: str,
*,
request_options: Optional[RequestOptions] = None,
stream: bool = False,
**kwargs: Any,
) -> httpx.Response:
"""
Expand All @@ -203,6 +222,9 @@ async def request(
method: HTTP method (GET, POST, etc.)
path: API endpoint path
request_options: Optional request-level overrides
stream: If True, return as soon as the response headers arrive and
leave the body unread. The caller must consume it with
`aiter_bytes()` and then call `aclose()` on the response.
**kwargs: Additional arguments to pass to httpx.request

Returns:
Expand All @@ -213,6 +235,20 @@ async def request(
"""
self._prepare_request_kwargs(request_options, kwargs)

if stream:
timeout = kwargs.pop("timeout", httpx.USE_CLIENT_DEFAULT)
http_request = self._client.build_request(
method, path, timeout=timeout, **kwargs
)
response = await self._client.send(http_request, stream=True)
if not response.is_success:
try:
await response.aread()
finally:
await response.aclose()
_raise_for_status(response)
return response

# Make the request
response = await self._client.request(method, path, **kwargs)

Expand Down
105 changes: 94 additions & 11 deletions src/fishaudio/core/iterators.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Audio stream wrappers with collection utilities."""

from collections.abc import AsyncIterator, Iterator
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from typing import Optional


class AudioStream:
Expand All @@ -21,21 +22,59 @@ class AudioStream:
# Or stream chunks manually
for chunk in client.tts.stream(text="Hello!"):
process_chunk(chunk)

# Use a with-block (or call close()) if you may stop early,
# so the HTTP connection is released right away
with client.tts.stream(text="Hello!") as stream:
for chunk in stream:
if done(chunk):
break
```
"""

def __init__(self, iterator: Iterator[bytes]):
def __init__(
self,
iterator: Iterator[bytes],
*,
on_close: Optional[Callable[[], None]] = None,
):
"""Initialize the audio iterator wrapper.

Args:
iterator: The underlying iterator of audio bytes
on_close: Called by close() to release the underlying resource,
for example the open HTTP response
"""
self._iter = iterator
self._on_close = on_close
self._closed = False

def __iter__(self) -> Iterator[bytes]:
"""Allow direct iteration over audio chunks."""
return self._iter

def close(self) -> None:
"""Stop the stream and release the underlying connection.

Safe to call more than once, and before iteration has started.
"""
if self._closed:
return
self._closed = True
try:
close_iter = getattr(self._iter, "close", None)
if close_iter is not None:
close_iter()
finally:
if self._on_close is not None:
self._on_close()

def __enter__(self) -> "AudioStream":
return self

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.close()

def collect(self) -> bytes:
"""Collect all audio chunks into a single bytes object.

Expand All @@ -52,10 +91,13 @@ def collect(self) -> bytes:
f.write(audio)
```
"""
chunks = []
for chunk in self._iter:
chunks.append(chunk)
return b"".join(chunks)
try:
chunks = []
for chunk in self._iter:
chunks.append(chunk)
return b"".join(chunks)
finally:
self.close()


class AsyncAudioStream:
Expand All @@ -77,21 +119,59 @@ class AsyncAudioStream:
# Or stream chunks manually
async for chunk in await client.tts.stream(text="Hello!"):
await process_chunk(chunk)

# Use async with (or await aclose()) if you may stop early,
# so the HTTP connection is released right away
async with await client.tts.stream(text="Hello!") as stream:
async for chunk in stream:
if done(chunk):
break
```
"""

def __init__(self, async_iterator: AsyncIterator[bytes]):
def __init__(
self,
async_iterator: AsyncIterator[bytes],
*,
on_close: Optional[Callable[[], Awaitable[None]]] = None,
):
"""Initialize the async audio iterator wrapper.

Args:
async_iterator: The underlying async iterator of audio bytes
on_close: Awaited by aclose() to release the underlying resource,
for example the open HTTP response
"""
self._iter = async_iterator
self._on_close = on_close
self._closed = False

def __aiter__(self) -> AsyncIterator[bytes]:
"""Allow direct async iteration over audio chunks."""
return self._iter

async def aclose(self) -> None:
"""Stop the stream and release the underlying connection.

Safe to call more than once, and before iteration has started.
"""
if self._closed:
return
self._closed = True
try:
close_iter = getattr(self._iter, "aclose", None)
if close_iter is not None:
await close_iter()
finally:
if self._on_close is not None:
await self._on_close()

async def __aenter__(self) -> "AsyncAudioStream":
return self

async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
await self.aclose()

async def collect(self) -> bytes:
"""Collect all audio chunks into a single bytes object.

Expand All @@ -109,7 +189,10 @@ async def collect(self) -> bytes:
f.write(audio)
```
"""
chunks = []
async for chunk in self._iter:
chunks.append(chunk)
return b"".join(chunks)
try:
chunks = []
async for chunk in self._iter:
chunks.append(chunk)
return b"".join(chunks)
finally:
await self.aclose()
32 changes: 21 additions & 11 deletions src/fishaudio/resources/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,22 +140,27 @@ def stream(

payload = request.model_dump(exclude_none=True)

# Make request with streaming
# Send the request and return once headers arrive; the body is read
# lazily so chunks reach the caller as the server produces them.
response = self._client.request(
"POST",
"/v1/tts",
headers={"Content-Type": "application/msgpack", "model": model},
content=ormsgpack.packb(payload),
request_options=request_options,
stream=True,
)

# Create generator and wrap with AudioStream
def _stream():
for chunk in response.iter_bytes():
if chunk:
yield chunk
try:
for chunk in response.iter_bytes():
if chunk:
yield chunk
finally:
response.close()
Comment on lines +156 to +161

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ef23521. AudioStream / AsyncAudioStream now own the response: close() / aclose() release it, both work as context managers, and collect() closes when done. Early exit is documented as with client.tts.stream(...) as stream: ... break.

Tests: test_with_block_closes_after_early_break, test_async_with_closes_after_early_break (fail before this commit, pass after).

Comment on lines +160 to +161

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Close live responses even when iteration never starts

If tts.stream() is abandoned before its first iteration, this finally never runs: closing or garbage-collecting an unstarted generator does not execute its body. The HTTP request has already been sent with stream=True, so the unread response remains open, unlike before when request() consumed and closed it. This also affects AsyncTTSClient.stream(), and the returned stream wrappers expose no public close/aclose to release the response. Repeated unused streams can therefore exhaust a long-lived client's connection pool. Give the returned wrapper ownership of the response and a cleanup path that works before iteration starts, rather than relying solely on generator finalization.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ef23521. The wrapper now holds the response, so close() / aclose() release it even if iteration never started (it no longer relies on generator finalization). Closing is idempotent; sync and async are both covered.

Tests: test_close_before_iteration_releases_response, test_aclose_before_iteration_releases_response (fail before this commit, pass after). Also verified against the live API.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

return AudioStream(_stream())
return AudioStream(_stream(), on_close=response.close)

def convert(
self,
Expand Down Expand Up @@ -450,22 +455,27 @@ async def stream(

payload = request.model_dump(exclude_none=True)

# Make request with streaming
# Send the request and return once headers arrive; the body is read
# lazily so chunks reach the caller as the server produces them.
response = await self._client.request(
"POST",
"/v1/tts",
headers={"Content-Type": "application/msgpack", "model": model},
content=ormsgpack.packb(payload),
request_options=request_options,
stream=True,
)

# Create async generator and wrap with AsyncAudioStream
async def _stream():
async for chunk in response.aiter_bytes():
if chunk:
yield chunk

return AsyncAudioStream(_stream())
try:
async for chunk in response.aiter_bytes():
if chunk:
yield chunk
finally:
await response.aclose()

return AsyncAudioStream(_stream(), on_close=response.aclose)

async def convert(
self,
Expand Down
Loading
Loading