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
1 change: 1 addition & 0 deletions .changes/resume-negotiation-failure-full-reconnect
Original file line number Diff line number Diff line change
@@ -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"
4 changes: 2 additions & 2 deletions lib/src/core/engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1314,9 +1314,9 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
_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;
}

Expand Down
8 changes: 7 additions & 1 deletion lib/src/core/transport.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
92 changes: 92 additions & 0 deletions test/core/resume_negotiation_failure_test.dart
Original file line number Diff line number Diff line change
@@ -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 = <StaleAnswerPeerConnection>[];
late E2EContainer container;
late MockWebSocketConnector ws;

setUp(() async {
resetMockDataChannels();
connections.clear();
container = E2EContainer(
peerConnectionCreate: (Map<String, dynamic> configuration, [Map<String, dynamic>? 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<void>.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<void>.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<void>.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',
);
});
}
19 changes: 19 additions & 0 deletions test/core/transport_negotiate_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<String, dynamic> configuration, [Map<String, dynamic>? constraints]) async => pc,
connectOptions: const ConnectOptions(),
);
addTearDown(transport.dispose);
final offers = <rtc.RTCSessionDescription>[];
transport.onOffer = offers.add;
pc.stale = true;

await expectLater(
transport.createAndSendOffer(const RTCOfferOptions(iceRestart: true)),
throwsA(isA<NegotiationError>()),
);
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(
Expand Down
8 changes: 6 additions & 2 deletions test/mock/e2e_container.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -38,14 +39,17 @@ class E2EContainer {
/// since [connectRoom] returned. Populated only when [captureOutbound] is true.
final List<lk_models.DataPacket> 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);
}
Expand Down
22 changes: 22 additions & 0 deletions test/mock/peerconnection_mock.dart
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,28 @@ a=rtpmap:32 MPV/90000
Future<void> 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<RTCSessionDescription?> getRemoteDescription() async =>
stale ? RTCSessionDescription('v=0\r\nprevious', 'answer') : super.getRemoteDescription();

@override
Future<void> 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);

Expand Down
Loading