Skip to content

Commit f110eef

Browse files
committed
fix(rtc): retain cleanup tasks in set and fail pending sid waiters on cancel or error
1 parent 0d32ef1 commit f110eef

2 files changed

Lines changed: 54 additions & 9 deletions

File tree

‎livekit-rtc/livekit/rtc/room.py‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ def __init__(
200200
self._server_url: str | None = None
201201
self._task: Optional[asyncio.Task] = None
202202
self._cleanup_task: Optional[asyncio.Task[None]] = None
203+
self._cleanup_tasks: set[asyncio.Task[None]] = set()
203204

204205
def __del__(self) -> None:
205206
if self._ffi_handle is not None:
@@ -226,6 +227,13 @@ def _resolve_first_sid(self, sid: str) -> None:
226227
if sid and not self._first_sid_future.done():
227228
self._first_sid_future.set_result(sid)
228229

230+
def _fail_sid_waiters(self, err: BaseException) -> None:
231+
fut = self._first_sid_future
232+
if not fut.done():
233+
fut.set_exception(err)
234+
fut.exception()
235+
self._first_sid_future = asyncio.Future[str]()
236+
229237
@property
230238
def local_participant(self) -> LocalParticipant:
231239
"""Gets the local participant in the room.
@@ -469,9 +477,9 @@ def on_participant_connected(participant):
469477
await room.connect("ws://localhost:7880", "your_token")
470478
```
471479
"""
472-
if self._cleanup_task is not None and not self._cleanup_task.done():
480+
if self._cleanup_tasks:
473481
try:
474-
await asyncio.shield(self._cleanup_task)
482+
await asyncio.shield(asyncio.gather(*self._cleanup_tasks))
475483
except Exception:
476484
pass
477485

@@ -576,15 +584,19 @@ def on_participant_connected(participant):
576584
cb: proto_ffi.FfiEvent = await queue.wait_for(
577585
lambda e: e.connect.async_id == resp.connect.async_id
578586
)
579-
except asyncio.CancelledError:
587+
except asyncio.CancelledError as e:
580588
# The connect request was already dispatched to the FFI server.
581589
# Transfer cleanup to a background task so the caller unblocks immediately,
582590
# while guaranteeing that when ConnectCallback arrives the FFI handshake is
583591
# completed and cleanly disconnected (Issues #784, #804).
584592
queue_unsubscribed = True
585-
self._cleanup_task = self._loop.create_task(
593+
task = self._loop.create_task(
586594
self._cleanup_cancelled_connect(queue, resp.connect.async_id, self._ffi_queue)
587595
)
596+
self._cleanup_task = task
597+
self._cleanup_tasks.add(task)
598+
task.add_done_callback(self._cleanup_tasks.discard)
599+
self._fail_sid_waiters(e)
588600
raise
589601
finally:
590602
if not queue_unsubscribed:
@@ -631,7 +643,7 @@ def on_participant_connected(participant):
631643
ready_req.ready_for_room_event.room_handle = self._ffi_handle.handle
632644
FfiClient.instance.request(ready_req)
633645
ready_sent = True
634-
except BaseException:
646+
except BaseException as e:
635647
if not ready_sent:
636648
if self._task is not None and not self._task.done():
637649
self._task.cancel()
@@ -641,8 +653,7 @@ def on_participant_connected(participant):
641653
self._remote_participants.clear()
642654
self._local_participant = None
643655
self._info = proto_room.RoomInfo()
644-
if self._first_sid_future.done():
645-
self._first_sid_future = asyncio.Future[str]()
656+
self._fail_sid_waiters(e)
646657
raise
647658

648659
@staticmethod
@@ -813,9 +824,9 @@ async def disconnect(
813824
) -> None:
814825
"""Disconnects from the room."""
815826
if not self.isconnected():
816-
if self._cleanup_task is not None and not self._cleanup_task.done():
827+
if self._cleanup_tasks:
817828
try:
818-
await asyncio.shield(self._cleanup_task)
829+
await asyncio.shield(asyncio.gather(*self._cleanup_tasks))
819830
except Exception:
820831
pass
821832
return

‎livekit-rtc/tests/test_room_connect_cancellation.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -457,3 +457,37 @@ def fake_request(req: proto_ffi.FfiRequest) -> proto_ffi.FfiResponse:
457457
connect_task2.cancel()
458458
with pytest.raises(asyncio.CancelledError):
459459
await connect_task2
460+
461+
462+
@pytest.mark.asyncio
463+
async def test_room_connect_cancellation_fails_sid_waiters(
464+
monkeypatch: pytest.MonkeyPatch,
465+
) -> None:
466+
room = Room()
467+
connect_async_id = 999
468+
469+
def fake_request(req: proto_ffi.FfiRequest) -> proto_ffi.FfiResponse:
470+
which = req.WhichOneof("message")
471+
if which == "connect":
472+
resp = proto_ffi.FfiResponse()
473+
resp.connect.async_id = connect_async_id
474+
return resp
475+
raise AssertionError(f"unexpected request: {which}")
476+
477+
monkeypatch.setattr(FfiClient.instance, "request", fake_request)
478+
479+
connect_task = asyncio.create_task(room.connect("ws://127.0.0.1:7880", "fake-token"))
480+
await asyncio.sleep(0)
481+
482+
sid_task = asyncio.create_task(room.sid)
483+
await asyncio.sleep(0)
484+
485+
connect_task.cancel()
486+
with pytest.raises(asyncio.CancelledError):
487+
await connect_task
488+
489+
with pytest.raises(asyncio.CancelledError):
490+
await sid_task
491+
492+
# Future SID waiter on the same room gets a fresh future
493+
assert not room._first_sid_future.done()

0 commit comments

Comments
 (0)