1111from livekit import api , rtc
1212
1313logger = logging .getLogger ("isaaccapture.remote_assistance.connection" )
14+ CONNECT_TIMEOUT_S = 15
15+ _pending_cleanup = set ()
1416
1517
1618def token_for (settings : dict , identity : str , * , publish : bool = True ) -> str :
@@ -32,6 +34,8 @@ def token_for(settings: dict, identity: str, *, publish: bool = True) -> str:
3234 )
3335 .to_jwt ()
3436 )
37+ if urlparse (settings ["url" ]).scheme not in ("wss" , "https" ):
38+ raise ValueError ("Production credentials require a wss:// or https:// URL" )
3539 env = settings .get ("token_env" , "LIVEKIT_TOKEN" )
3640 token = os .environ .get (env )
3741 if not token :
@@ -41,18 +45,35 @@ def token_for(settings: dict, identity: str, *, publish: bool = True) -> str:
4145
4246async def connect (room : rtc .Room , settings : dict , identity : str , * , publish = True ):
4347 token = token_for (settings , identity , publish = publish )
44- async with asyncio .timeout ( 15 ):
45- await room .connect (
48+ joining = asyncio .create_task (
49+ room .connect (
4650 settings ["url" ],
4751 token ,
4852 options = rtc .RoomOptions (auto_subscribe = False , dynacast = False ),
4953 )
54+ )
55+ try :
56+ await asyncio .wait_for (asyncio .shield (joining ), CONNECT_TIMEOUT_S )
57+ except BaseException :
58+ # The SDK assigns its handle late; cancellation cannot safely reclaim the room.
59+ cleanup = asyncio .create_task (_disconnect_late_room (joining , room ))
60+ _pending_cleanup .add (cleanup )
61+ cleanup .add_done_callback (_pending_cleanup .discard )
62+ raise
5063 if room .local_participant .identity != identity or room .name != settings ["room" ]:
5164 await room .disconnect ()
5265 raise ValueError ("Token identity/room does not match the configured endpoint" )
5366 logger .info ("Joined room %s as %s" , room .name , identity )
5467
5568
69+ async def _disconnect_late_room (joining , room ):
70+ try :
71+ await joining
72+ await disconnect (room )
73+ except Exception :
74+ logger .debug ("Late LiveKit connection cleanup failed" , exc_info = True )
75+
76+
5677async def disconnect (room : rtc .Room ):
5778 try :
5879 async with asyncio .timeout (5 ):
0 commit comments