From 6bf771c6cb670904cd7770110b08b04edd2b8108 Mon Sep 17 00:00:00 2001 From: j-mercker Date: Sun, 22 Nov 2026 07:51:20 -0500 Subject: [PATCH] Fall back to a full reconnect when a resume cannot renegotiate the publisher --- .../resume-negotiation-failure-full-reconnect | 1 + lib/src/core/engine.dart | 4 +- lib/src/core/transport.dart | 8 +- .../core/resume_negotiation_failure_test.dart | 92 +++++++++++++++++++ test/core/transport_negotiate_test.dart | 19 ++++ test/mock/e2e_container.dart | 8 +- test/mock/peerconnection_mock.dart | 22 +++++ 7 files changed, 149 insertions(+), 5 deletions(-) create mode 100644 .changes/resume-negotiation-failure-full-reconnect create mode 100644 test/core/resume_negotiation_failure_test.dart diff --git a/.changes/resume-negotiation-failure-full-reconnect b/.changes/resume-negotiation-failure-full-reconnect new file mode 100644 index 000000000..6fb2d7995 --- /dev/null +++ b/.changes/resume-negotiation-failure-full-reconnect @@ -0,0 +1 @@ +patch type="fixed" "A resume that cannot restore the publisher's previous answer now falls back to a full reconnect instead of retrying until the reconnect attempts run out" diff --git a/lib/src/core/engine.dart b/lib/src/core/engine.dart index 48c9d227f..acea6dbe6 100644 --- a/lib/src/core/engine.dart +++ b/lib/src/core/engine.dart @@ -1314,9 +1314,9 @@ class Engine extends Disposable with EventsEmittable { _reconnectAttempts = _reconnectAttempts + 1; logger.fine('attemptReconnect: ${fullReconnect ? 'full reconnect' : 'resume'} failed: $e'); bool recoverable = true; - if (fullReconnect || e is WebSocketException || e is MediaConnectException) { + if (fullReconnect || e is WebSocketException || e is MediaConnectException || e is NegotiationError) { // a failed full reconnect stays a full reconnect; a resume that failed - // at the transport or media layer cannot be resumed again + // at the transport, media or negotiation layer cannot be resumed again fullReconnectOnNext = true; } diff --git a/lib/src/core/transport.dart b/lib/src/core/transport.dart index 7c2ce57de..1ddbb1682 100644 --- a/lib/src/core/transport.dart +++ b/lib/src/core/transport.dart @@ -393,7 +393,13 @@ class Transport extends Disposable { renegotiate = true; return; } - await pc.setRemoteDescription(currentSD); + try { + await pc.setRemoteDescription(currentSD); + } catch (e) { + // The previous answer no longer fits the unanswered offer (one that added or removed a track, for example), + // and the publisher stays in have-local-offer, so resuming again fails the same way. + throw NegotiationError('could not restore the remote description for ICE restart: $e'); + } } if (restartingIce && !lkPlatformIs(PlatformType.web)) { diff --git a/test/core/resume_negotiation_failure_test.dart b/test/core/resume_negotiation_failure_test.dart new file mode 100644 index 000000000..e462785be --- /dev/null +++ b/test/core/resume_negotiation_failure_test.dart @@ -0,0 +1,92 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// A resume that fails because the publisher cannot negotiate must be followed by a full +// reconnect: the publisher stays in have-local-offer, so resuming again fails the same way. + +@Timeout(Duration(seconds: 10)) +library; + +import 'package:flutter_test/flutter_test.dart'; + +import 'package:livekit_client/src/proto/livekit_rtc.pb.dart' as lk_rtc; +import '../mock/e2e_container.dart'; +import '../mock/peerconnection_mock.dart'; +import '../mock/websocket_mock.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final connections = []; + late E2EContainer container; + late MockWebSocketConnector ws; + + setUp(() async { + resetMockDataChannels(); + connections.clear(); + container = E2EContainer( + peerConnectionCreate: (Map configuration, [Map? constraints]) async { + final pc = StaleAnswerPeerConnection(); + connections.add(pc); + return pc; + }, + ); + ws = container.wsConnector; + await container.connectRoom(); + }); + + tearDown(() async { + await container.dispose(); + }); + + test('a resume that fails with a NegotiationError is retried as a full reconnect', () async { + // Negotiating marks the publisher as having published. + await container.engine.negotiate(); + // Let the debounced negotiation finish before the publisher is made stale. + await Future.delayed(const Duration(milliseconds: 100)); + for (final pc in connections) { + pc.stale = true; + } + + var resumeHandlers = ws.handlers; + ws.onDispose(); + for (var i = 0; i < 200 && identical(ws.handlers, resumeHandlers); i++) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect( + ws.uri?.queryParameters['reconnect'], + '1', + reason: 'the first attempt must be a resume', + ); + + resumeHandlers = ws.handlers; + ws.onData( + lk_rtc.SignalResponse(reconnect: lk_rtc.ReconnectResponse()).writeToBuffer(), + ); + + for (var i = 0; i < 200 && identical(ws.handlers, resumeHandlers); i++) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect( + identical(ws.handlers, resumeHandlers), + isFalse, + reason: 'no attempt followed the failed resume', + ); + expect( + ws.uri?.queryParameters['reconnect'], + isNull, + reason: 'the next attempt must re-join, not resume', + ); + }); +} diff --git a/test/core/transport_negotiate_test.dart b/test/core/transport_negotiate_test.dart index 30eb06b62..14611622d 100644 --- a/test/core/transport_negotiate_test.dart +++ b/test/core/transport_negotiate_test.dart @@ -22,6 +22,7 @@ import 'package:flutter_webrtc/flutter_webrtc.dart' as rtc; import 'package:livekit_client/src/core/transport.dart' show Transport; import 'package:livekit_client/src/exceptions.dart' show NegotiationError; +import 'package:livekit_client/src/internal/types.dart' show RTCOfferOptions; import 'package:livekit_client/src/options.dart' show ConnectOptions; import '../mock/peerconnection_mock.dart'; @@ -61,6 +62,24 @@ class _SlowRemoteDescriptionPeerConnection extends MockPeerConnection { void main() { group('Transport.negotiate', () { + test('an ICE restart that cannot restore the previous answer throws a NegotiationError', () async { + final pc = StaleAnswerPeerConnection(); + final transport = await Transport.create( + (Map configuration, [Map? constraints]) async => pc, + connectOptions: const ConnectOptions(), + ); + addTearDown(transport.dispose); + final offers = []; + transport.onOffer = offers.add; + pc.stale = true; + + await expectLater( + transport.createAndSendOffer(const RTCOfferOptions(iceRestart: true)), + throwsA(isA()), + ); + expect(offers, isEmpty); + }); + test('sends an offer that was requested while the answer to the previous one is applied', () async { final pc = _SlowRemoteDescriptionPeerConnection(); final transport = await Transport.create( diff --git a/test/mock/e2e_container.dart b/test/mock/e2e_container.dart index 5a9965ae5..228e49cec 100644 --- a/test/mock/e2e_container.dart +++ b/test/mock/e2e_container.dart @@ -21,6 +21,7 @@ import 'package:flutter_webrtc/flutter_webrtc.dart' show RTCDataChannelMessage; import 'package:livekit_client/livekit_client.dart'; import 'package:livekit_client/src/core/engine.dart'; import 'package:livekit_client/src/core/signal_client.dart'; +import 'package:livekit_client/src/core/transport.dart' show PeerConnectionCreate; import 'package:livekit_client/src/proto/livekit_models.pb.dart' as lk_models; import 'package:livekit_client/src/proto/livekit_rtc.pb.dart' as lk_rtc; import '../core/signal_client_test.dart'; @@ -38,14 +39,17 @@ class E2EContainer { /// since [connectRoom] returned. Populated only when [captureOutbound] is true. final List capturedDataPackets = []; - E2EContainer({RoomOptions roomOptions = const RoomOptions()}) { + E2EContainer({ + RoomOptions roomOptions = const RoomOptions(), + PeerConnectionCreate peerConnectionCreate = MockPeerConnection.create, + }) { wsConnector = MockWebSocketConnector(); client = SignalClient(wsConnector.connect); engine = Engine( connectOptions: const ConnectOptions(), roomOptions: roomOptions, signalClient: client, - peerConnectionCreate: MockPeerConnection.create, + peerConnectionCreate: peerConnectionCreate, ); room = Room(engine: engine); } diff --git a/test/mock/peerconnection_mock.dart b/test/mock/peerconnection_mock.dart index 5e31ad29e..c96e0cf4b 100644 --- a/test/mock/peerconnection_mock.dart +++ b/test/mock/peerconnection_mock.dart @@ -307,6 +307,28 @@ a=rtpmap:32 MPV/90000 Future restartIce() => throw UnimplementedError(); } +/// A peer connection that, once [stale] is set, still waits for the answer to its last offer and cannot take the +/// previous answer back, as after an unanswered offer that added or removed a track. +class StaleAnswerPeerConnection extends MockPeerConnection { + bool stale = false; + + @override + RTCSignalingState? get signalingState => + stale ? RTCSignalingState.RTCSignalingStateHaveLocalOffer : super.signalingState; + + @override + Future getRemoteDescription() async => + stale ? RTCSessionDescription('v=0\r\nprevious', 'answer') : super.getRemoteDescription(); + + @override + Future setRemoteDescription(RTCSessionDescription description) async { + if (stale) { + throw Exception('InvalidAccessError: The order of m-lines in answer doesn\'t match order in offer.'); + } + await super.setRemoteDescription(description); + } +} + class MockRtpSender implements RTCRtpSender { MockRtpSender(this.track);