Repository navigation
fix: ignore callbacks from a signal socket that was already replaced #1211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
20135bb
299ab52
d9035f2
ef6abd1
bbcede5
f116f50
f8a72be
6897e90
9552119
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| patch type="fixed" "A late close from a signal socket the SDK already replaced no longer starts another reconnect. In a browser it arrives up to seconds later, which made a room resume every 2 s after its first reconnect. A signal connect that only opens after disconnect() or a newer connect() is closed instead of taking over the connection" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -43,6 +43,16 @@ class SignalClient extends Disposable with EventsEmittable<SignalEvent> { | |
| ConnectionState get connectionState => _connectionState; | ||
|
|
||
| final WebSocketConnector _wsConnector; | ||
|
|
||
| // Id of the socket whose callbacks are honored. connect() gives each new | ||
| // socket the next id, and cleanUp() advances it too so the socket it disposes | ||
| // stops being current. A real socket reports its close after dispose() | ||
| // returns, a few milliseconds later on a good path but seconds later in a | ||
| // browser when the server keeps TCP open after the close handshake. That | ||
| // report used to be attributed to whatever connection was current by then, | ||
| // clobbering its state and starting a reconnect against a healthy socket, | ||
| // over and over when every reconnect replaced the socket again. | ||
| int _socketId = 0; | ||
| LiveKitWebSocket? _ws; | ||
|
|
||
| final _queue = Queue<lk_rtc.SignalRequest>(); | ||
|
|
@@ -144,6 +154,8 @@ class SignalClient extends Disposable with EventsEmittable<SignalEvent> { | |
|
|
||
| logger.fine('SignalClient connecting with url: ${rtcUri.redactingAccessToken}'); | ||
|
|
||
| // Id of the socket this attempt opens, set once the previous one is gone. | ||
| int? socketId; | ||
| try { | ||
| if (reconnect == true) { | ||
| _connectionState = ConnectionState.reconnecting; | ||
|
|
@@ -154,25 +166,38 @@ class SignalClient extends Disposable with EventsEmittable<SignalEvent> { | |
| } | ||
| // Clean up existing socket | ||
| await cleanUp(); | ||
| // Attempt to connect | ||
| var future = _wsConnector( | ||
| // Attempt to connect. Callbacks carry the id of the socket they belong to | ||
| // so a late report from a replaced socket is ignored. | ||
| final id = socketId = ++_socketId; | ||
| final ws = await _wsConnector( | ||
|
Comment on lines
+169
to
+172
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Stale resume rejects a newer join If a resume finishes closing its old socket during a new join’s handshake, Learn moreA server migration requesting Example: A migration starts a resume and waits for socket A to close. The app leaves and starts joining another room on socket B. A finishes closing before B opens, so the stale resume claims the current ID. B opens successfully but the SDK disposes it and fails the join. Recommended fix: Reserve ownership of the connection attempt before asynchronous preparation and teardown. Let Was this helpful? React with 👍 or 👎 to provide feedback. |
||
| rtcUri, | ||
| options: WebSocketEventHandlers( | ||
| onData: _onSocketData, | ||
| onDispose: _onSocketDispose, | ||
| onError: _onSocketError, | ||
| onData: (data) => _ifCurrentSocket(id, () => _onSocketData(data)), | ||
| onDispose: () => _ifCurrentSocket(id, _onSocketDispose), | ||
| onError: (error) => _ifCurrentSocket(id, () => _onSocketError(error)), | ||
| ), | ||
| headers: { | ||
| 'Authorization': 'Bearer $token', | ||
| }, | ||
| networkOptions: roomOptions.networkOptions, | ||
| ); | ||
| future = future.timeout(connectOptions.timeouts.connection); | ||
| _ws = await future; | ||
| ).timeout(connectOptions.timeouts.connection); | ||
| if (id != _socketId) { | ||
| // disconnect() or a newer connect() took over while this socket was | ||
| // opening. Installing it would take the place of the current one. | ||
| await ws.dispose(); | ||
| throw const SignalConnectSupersededException(); | ||
|
Comment on lines
+184
to
+188
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔴 Stale join disables Android call routing When a cancelled join opens after a successful rejoin, Learn moreRoom.connect starts native audio before it opens the signal socket. Room._cleanUp stops audio when the app disconnects, and the next join starts it again. When the first socket finally opens, the superseded exception passes through Engine._connect, but the original Room.connect still runs its failure cleanup. In SDK-managed Android mode, NativeAudioManagement.stop stops the shared session, and LKAudioSwitchManager.stop tears down focus and routing rather than releasing an attempt-specific resource. Example: An Android app cancels a slow join and then joins another room. The new call starts with Bluetooth routing. The first handshake completes late and its error cleanup stops the audio session still in use by the new call. Recommended fix: Track which room connection attempt owns the native audio setup and make failure cleanup conditional on that ownership. A superseded attempt must not stop audio after a newer attempt has taken ownership. Extend the delayed-handshake regression test to assert that the stale completion causes no extra native audio stop. Was this helpful? React with 👍 or 👎 to provide feedback. |
||
| } | ||
| _ws = ws; | ||
| // Successful connection | ||
| _connectionState = ConnectionState.connected; | ||
| events.emit(const SignalConnectedEvent()); | ||
| } catch (socketError) { | ||
| // An attempt that something else replaced leaves the state and the | ||
| // events to the connection that replaced it. | ||
| if (socketId != null && socketId != _socketId) { | ||
| if (socketError is SignalConnectSupersededException) rethrow; | ||
| throw const SignalConnectSupersededException(); | ||
| } | ||
| if (socketError is CertificatePinningException) { | ||
| // In reconnect mode the engine owns state and event emission, | ||
| // emitting here would race its reconnect handling. | ||
|
|
@@ -242,11 +267,15 @@ class SignalClient extends Disposable with EventsEmittable<SignalEvent> { | |
| @internal | ||
| Future<void> cleanUp() async { | ||
| logger.fine('[${objectId}] cleanUp()'); | ||
| _socketId++; | ||
| _connectionState = ConnectionState.disconnected; | ||
| await _ws?.dispose(); | ||
| // Detached before the await, so a connect() that runs while the old | ||
| // socket is still closing keeps its own socket, queue and pings. | ||
| final ws = _ws; | ||
| _ws = null; | ||
| _queue.clear(); | ||
| _clearPingInterval(); | ||
| await ws?.dispose(); | ||
| } | ||
|
|
||
| void _sendRequest( | ||
|
|
@@ -409,6 +438,31 @@ class SignalClient extends Disposable with EventsEmittable<SignalEvent> { | |
| } | ||
| } | ||
|
|
||
| void _ifCurrentSocket(int socketId, void Function() action) { | ||
| if (socketId != _socketId) { | ||
| logger.fine('[$objectId] ignoring a callback from a socket that was already replaced'); | ||
| return; | ||
| } | ||
| action(); | ||
| } | ||
|
|
||
| /// Drops the signal socket the way a server side close does: the socket goes | ||
| /// away and the engine sees a disconnect it has to recover from. For the | ||
| /// debug scenarios and the connection checker. [cleanUp] alone is a quiet | ||
| /// teardown, the disposed socket's own close is ignored. | ||
| @internal | ||
| Future<void> simulateSignalDrop() async { | ||
| if (_ws == null) { | ||
| logger.fine('[$objectId] simulateSignalDrop(): no signal socket to drop'); | ||
| return; | ||
| } | ||
| // The loss is reported before the socket has finished closing, which can | ||
| // take a while, so it is charged to the socket that was dropped. | ||
| final dropped = cleanUp(); | ||
| _onSocketDispose(); | ||
| await dropped; | ||
| } | ||
|
|
||
| void _onSocketError(dynamic error) { | ||
| logger.warning('received websocket error $error'); | ||
| } | ||
|
|
@@ -629,3 +683,14 @@ extension SignalClientInternalMethods on SignalClient { | |
| @internal | ||
| void clearQueue() => _queue.clear(); | ||
| } | ||
|
|
||
| /// Thrown by a [SignalClient.connect] whose socket was no longer wanted by the | ||
| /// time it opened, because disconnect() or a newer connect() took over. The | ||
| /// connection that took over owns the state and the events. | ||
| @internal | ||
| class SignalConnectSupersededException implements Exception { | ||
| const SignalConnectSupersededException(); | ||
|
|
||
| @override | ||
| String toString() => 'SignalConnectSupersededException: the signal connection was superseded while it was opening'; | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 Cancelled reconnect restarts the new room
When a full reconnect opens after the app leaves and rejoins,
SignalConnectSupersededExceptionstill reaches reconnect recovery. attemptReconnect treats it as retryable and restarts the healthy session.Learn more
A server-requested full reconnect opens a fresh signaling socket through restartConnection. The app can disconnect during that handshake and reuse the room; Engine.connect clears
_isClosedand _connect replaces the URL and token. When the old handshake returns, SignalClient.connect discards it with a superseded exception. Without another region, restartConnection propagates that exception, and attemptReconnect setsfullReconnectOnNextand queues a retry. The engine is open again, so the retry tears down the new room's transports in restartConnection. With a regional fallback,restartConnectioncan start another handshake directly instead of propagating cancellation.Example: Room A starts a full reconnect. The app leaves A and successfully joins B using the same
Room. A's handshake returns late; the old retry starts a full reconnect of B even though B is healthy.Recommended fix: Propagate supersession past regional failover and treat it as cancellation, not failure, in
attemptReconnect. Scope the attempt's retry bookkeeping andfinallycleanup to the session that started it. Test a full reconnect held at the handshake while the app disconnects and joins again, then verify that releasing the stale handshake opens no further sockets.Was this helpful? React with 👍 or 👎 to provide feedback.