Skip to content
Merged
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/single-disconnect-event
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
patch type="fixed" "Emit a single disconnected event when connecting fails"
29 changes: 15 additions & 14 deletions lib/src/core/engine.dart
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,16 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
} catch (error) {
logger.fine('Connect Error $error');

events.emit(EngineDisconnectedEvent(
reason: DisconnectReason.joinFailure,
));
// during a reconnect this connect() runs inside restartConnection and
// attemptReconnect owns disconnect emission, emitting here as well
// would produce two events for one failure
if (!_isReconnecting && !_attemptingReconnect) {
events.emit(EngineDisconnectedEvent(
reason: error is CertificatePinningException
? DisconnectReason.signalingConnectionFailure
: DisconnectReason.joinFailure,
));
}
rethrow;
}
}
Expand Down Expand Up @@ -1367,18 +1374,12 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
if (event.reason == DisconnectReason.disconnected && !_isClosed) {
await handleReconnect(ClientDisconnectReason.signal,
reconnectReason: lk_models.ReconnectReason.RR_SIGNAL_DISCONNECTED);
} else if (event.reason == DisconnectReason.signalingConnectionFailure) {
// while reconnecting, attemptReconnect owns disconnect handling and
// emits EngineDisconnectedEvent itself, relaying here as well would
// race it with a duplicate event. _attemptingReconnect covers the
// window where cleanUp() has already reset _isReconnecting but
// attemptReconnect has not finished its error handling yet
if (!_isReconnecting && !_attemptingReconnect) {
events.emit(EngineDisconnectedEvent(
reason: event.reason,
));
}
}
// signalingConnectionFailure is intentionally not relayed as
// EngineDisconnectedEvent here. The signal client emits it while the
// connect() call is failing, so connect()'s own catch (initial connect)
// or attemptReconnect (reconnect) already emits the engine event, and
// relaying here produced a duplicate disconnect per failure.
})
..on<SignalOfferEvent>((event) async {
if (subscriber == null) {
Expand Down
114 changes: 114 additions & 0 deletions test/core/disconnect_event_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// 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.

@Timeout(Duration(seconds: 5))
library;

import 'package:flutter_test/flutter_test.dart';

import 'package:livekit_client/livekit_client.dart';
import 'package:livekit_client/src/internal/events.dart';
import 'package:livekit_client/src/support/websocket.dart';
import 'package:livekit_client/src/types/internal.dart';
import '../mock/e2e_container.dart';

const exampleUri = 'ws://www.example.com';
const token = 'token';

void main() {
TestWidgetsFlutterBinding.ensureInitialized();

late E2EContainer container;

setUp(() {
container = E2EContainer();
});

tearDown(() async {
await container.dispose();
});

test('emits exactly one disconnected event when pinning fails on initial connect', () async {
container.wsConnector.connectError =
CertificatePinningException('Certificate pin mismatch', host: 'www.example.com');

final disconnectedEvents = <RoomDisconnectedEvent>[];
container.room.events.listen((event) {
if (event is RoomDisconnectedEvent) {
disconnectedEvents.add(event);
}
});

await expectLater(
container.room.connect(exampleUri, token),
throwsA(isA<CertificatePinningException>()),
);

// allow all pending event deliveries to complete
await Future<void>.delayed(const Duration(milliseconds: 100));

expect(disconnectedEvents, hasLength(1));
expect(disconnectedEvents.single.reason, DisconnectReason.signalingConnectionFailure);
});

test('emits exactly one disconnected event when initial connect fails', () async {
container.wsConnector.connectError = WebSocketException('Failed to connect');

final disconnectedEvents = <RoomDisconnectedEvent>[];
container.room.events.listen((event) {
if (event is RoomDisconnectedEvent) {
disconnectedEvents.add(event);
}
});

await expectLater(
container.room.connect(exampleUri, token),
throwsA(isA<Exception>()),
);

await Future<void>.delayed(const Duration(milliseconds: 100));

expect(disconnectedEvents, hasLength(1));
expect(disconnectedEvents.single.reason, DisconnectReason.joinFailure);
});

test('emits exactly one disconnected event when pinning fails during a full reconnect', () async {
await container.connectRoom();

final engineDisconnectedEvents = <EngineDisconnectedEvent>[];
container.engine.events.listen((event) {
if (event is EngineDisconnectedEvent) {
engineDisconnectedEvents.add(event);
}
});
final roomDisconnectedEvents = <RoomDisconnectedEvent>[];
container.room.events.listen((event) {
if (event is RoomDisconnectedEvent) {
roomDisconnectedEvents.add(event);
}
});

container.wsConnector.connectError =
CertificatePinningException('Certificate pin mismatch', host: 'www.example.com');
container.engine.fullReconnectOnNext = true;
await container.engine.attemptReconnect(ClientDisconnectReason.reconnectRetry);

await Future<void>.delayed(const Duration(milliseconds: 100));

expect(engineDisconnectedEvents, hasLength(1));
expect(engineDisconnectedEvents.single.reason, DisconnectReason.signalingConnectionFailure);
expect(roomDisconnectedEvents, hasLength(1));
expect(roomDisconnectedEvents.single.reason, DisconnectReason.signalingConnectionFailure);
});
}
Loading