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
70 changes: 58 additions & 12 deletions src/fishaudio/resources/tts.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import asyncio
import base64
import binascii
import contextlib
import functools
import inspect
import json
Expand Down Expand Up @@ -1076,19 +1077,64 @@ async def text_generator():
) as ws:

async def sender():
await ws.send_bytes(
ormsgpack.packb(StartEvent(request=tts_request).model_dump())
)
# Normalize strings to TextEvent
async for item in text_stream:
event = _normalize_to_event(item)
await ws.send_bytes(ormsgpack.packb(event.model_dump()))
await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump()))
try:
await ws.send_bytes(
ormsgpack.packb(StartEvent(request=tts_request).model_dump())
)
# Normalize strings to TextEvent
async for item in text_stream:
event = _normalize_to_event(item)
await ws.send_bytes(ormsgpack.packb(event.model_dump()))
await ws.send_bytes(ormsgpack.packb(CloseEvent().model_dump()))
finally:
if inspect.isasyncgen(text_stream):
with contextlib.suppress(Exception):
await text_stream.aclose()

sender_task = asyncio.create_task(sender())
audio_iter = aiter_websocket_audio(ws)
next_chunk: Optional[asyncio.Task[bytes]] = None

# Process incoming audio messages
async for audio_chunk in aiter_websocket_audio(ws):
yield audio_chunk
async def _next_audio() -> bytes:
return await audio_iter.__anext__()

await sender_task
try:
# Process incoming audio messages
while True:
if sender_task.done():
await sender_task
async for audio_chunk in audio_iter:
yield audio_chunk
break
next_chunk = asyncio.create_task(_next_audio())
done, _ = await asyncio.wait(
{next_chunk, sender_task},
return_when=asyncio.FIRST_COMPLETED,
)
if next_chunk not in done:
await sender_task
Comment on lines +1114 to +1115
try:
audio_chunk = await next_chunk
except StopAsyncIteration:
break
finally:
next_chunk = None
yield audio_chunk
await sender_task
finally:
if next_chunk is not None:
if not next_chunk.done():
next_chunk.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
await next_chunk
elif not next_chunk.cancelled():
next_chunk.exception()
if inspect.isasyncgen(audio_iter):
with contextlib.suppress(Exception):
await audio_iter.aclose()
if not sender_task.done():
sender_task.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
await sender_task
Comment on lines +1135 to +1138
elif not sender_task.cancelled():
sender_task.exception()
148 changes: 148 additions & 0 deletions tests/unit/test_tts_realtime.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
"""Tests for TTS realtime streaming."""

import asyncio
import gc
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import ormsgpack
import pytest

from fishaudio import AsyncFishAudio
from fishaudio.core import AsyncClientWrapper, ClientWrapper, WebSocketOptions
from fishaudio.exceptions import WebSocketError
from fishaudio.resources.tts import AsyncTTSClient, TTSClient
from fishaudio.types import FlushEvent, Prosody, ReferenceAudio, TextEvent, TTSConfig

from .realtime_server import RealtimeServer


@pytest.fixture
def mock_client_wrapper(mock_api_key):
Expand Down Expand Up @@ -722,3 +728,145 @@ async def text_stream():
assert (
mock_aconnect_ws.call_args[1]["keepalive_ping_timeout_seconds"] == 60.0
)


class TestAsyncTTSRealtimeCleanup:
"""Real-transport cleanup tests for AsyncTTSClient.stream_websocket."""

@pytest.mark.asyncio
async def test_stream_websocket_cancels_sender_on_server_error(self):
unhandled = []
loop = asyncio.get_running_loop()
previous_handler = loop.get_exception_handler()
loop.set_exception_handler(lambda _loop, ctx: unhandled.append(ctx))

def error_script(conn):
start = conn.recv()
assert start["event"] == "start"
conn.send({"event": "audio", "audio": b"chunk1"})
conn.send({"event": "finish", "reason": "error"})

server = RealtimeServer(error_script)
stream_closed = False

async def slow_text_stream():
nonlocal stream_closed
try:
for i in range(5):
yield f"word {i}"
await asyncio.sleep(0.05)
finally:
stream_closed = True

try:
async with AsyncFishAudio(api_key="test", base_url=server.url) as client:
received = []
with pytest.raises(WebSocketError):
async for chunk in client.tts.stream_websocket(slow_text_stream()):
received.append(chunk)

await asyncio.sleep(0.15)
gc.collect()
await asyncio.sleep(0)
await asyncio.to_thread(server.stop)
finally:
loop.set_exception_handler(previous_handler)

assert received == [b"chunk1"]
assert stream_closed is True
assert unhandled == []

@pytest.mark.asyncio
async def test_stream_websocket_cancels_sender_on_early_close(self):
unhandled = []
loop = asyncio.get_running_loop()
previous_handler = loop.get_exception_handler()
loop.set_exception_handler(lambda _loop, ctx: unhandled.append(ctx))

def streaming_script(conn):
start = conn.recv()
assert start["event"] == "start"
conn.send({"event": "audio", "audio": b"chunk1"})
conn.send({"event": "audio", "audio": b"chunk2"})
conn.wait_gone()

server = RealtimeServer(streaming_script)
stream_closed = False

async def slow_text_stream():
nonlocal stream_closed
try:
for i in range(10):
yield f"word {i}"
await asyncio.sleep(0.05)
finally:
stream_closed = True

try:
async with AsyncFishAudio(api_key="test", base_url=server.url) as client:
gen = client.tts.stream_websocket(slow_text_stream())
try:
received = []
async for chunk in gen:
received.append(chunk)
break
finally:
await gen.aclose()

await asyncio.sleep(0.15)
gc.collect()
await asyncio.sleep(0)
await asyncio.to_thread(server.stop)
finally:
loop.set_exception_handler(previous_handler)

assert received == [b"chunk1"]
assert stream_closed is True
assert unhandled == []

@pytest.mark.asyncio
async def test_stream_websocket_propagates_sender_error_without_hanging(self):
unhandled = []
loop = asyncio.get_running_loop()
previous_handler = loop.get_exception_handler()
loop.set_exception_handler(lambda _loop, ctx: unhandled.append(ctx))

def wait_for_stop(conn):
start = conn.recv()
assert start["event"] == "start"
while True:
msg = conn.recv()
if msg["event"] == "stop":
conn.send({"event": "finish", "reason": "stop"})
break
conn.send({"event": "audio", "audio": b"chunk1"})

server = RealtimeServer(wait_for_stop)

async def failing_text_stream():
yield "hello"
await asyncio.sleep(0.02)
raise ValueError("text stream failed")

try:
async with AsyncFishAudio(api_key="test", base_url=server.url) as client:

async def consume():
chunks = []
async for chunk in client.tts.stream_websocket(
failing_text_stream()
):
chunks.append(chunk)
return chunks

with pytest.raises(ValueError, match="text stream failed"):
await asyncio.wait_for(consume(), timeout=2.0)

await asyncio.sleep(0.05)
gc.collect()
await asyncio.sleep(0)
await asyncio.to_thread(server.stop)
finally:
loop.set_exception_handler(previous_handler)

assert unhandled == []