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/disconnect-completes-on-socket-close
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
patch type="fixed" "disconnect() tears the room down locally after sending the Leave instead of waiting for the server to echo it, so it no longer stalls 10 s when the echo is lost. Overlapping disconnect() calls share one teardown and report one disconnect"
28 changes: 19 additions & 9 deletions lib/src/core/engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,8 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
})
..on<SignalDisconnectedEvent>((event) async {
logger.fine('Signal disconnected ${event.reason}');
// disconnect() marks the engine closed before it tears anything down,
// so a close that arrives during that teardown starts no reconnect
if (event.reason == DisconnectReason.disconnected && !_isClosed) {
await handleReconnect(
ClientDisconnectReason.signal,
Expand Down Expand Up @@ -1736,6 +1738,12 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
await handleReconnect(ClientDisconnectReason.leaveReconnect);
} else {
// DISCONNECT or v12 server with canReconnect=false
if (_isClosed) {
// the echo of our own Leave, or a server Leave that raced
// disconnect(). The local teardown has run or is running.
logger.fine('[Signal] Leave received after disconnect() started, ignoring');
return;
}
await signalClient.cleanUp();
fullReconnectOnNext = false;
await disconnect(reason: event.reason.toSDKType());
Expand Down Expand Up @@ -1767,17 +1775,19 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
}) async {
markClosed();
if (connectionState == ConnectionState.connected) {
// Tell the server, then tear down locally without waiting for its Leave
// echo, the same as the other SDKs. The echo is not guaranteed: media
// nodes drop queued leave messages when they close the signal sink, and
// waiting for it cost a 10 s timeout whenever it was lost.
await signalClient.sendLeave();
} else {
if (isPendingReconnect) {
logger.fine('disconnect: Cancel the reconnection processing!');
await signalClient.cleanUp();
await _signalListener.cancelAll();
_clearPendingReconnect();
}
await cleanUp();
events.emit(EngineDisconnectedEvent(reason: reason));
} else if (isPendingReconnect) {
logger.fine('disconnect: Cancel the reconnection processing!');
await signalClient.cleanUp();
await _signalListener.cancelAll();
_clearPendingReconnect();
}
await cleanUp();

@devin-ai-integration devin-ai-integration Bot Oct 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Old socket close disrupts immediate reconnect

When connect() follows disconnect(), the old socket's delayed close can mark the new connection disconnected. SignalClient._onSocketDispose does not distinguish the old socket from the new one, triggering an unnecessary reconnect.

Learn more

The signaling client stores connection state for the current socket, but each socket retains the same _onSocketDispose callback. On web, LiveKitWebSocketWeb calls WebSocket.close() without waiting for the later onClose event. SignalClient.cleanUp therefore finishes before the old callback runs. A subsequent connect can install a new socket before SignalClient._onSocketDispose receives the old close and marks that new connection disconnected.

Example: Disconnect session A on web, then immediately connect session B on the same Room. If A's onClose fires after B connects, B is marked disconnected and the engine begins reconnecting despite B's live socket.

Recommended fix: Bind close callbacks to the socket or connection generation that created them. Ignore closes from sockets that are no longer current; add a web-style delayed-close regression test after reconnect.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid, this is the case #1211 covers. It is stacked on this PR and they merge together. SignalClient now tags each socket's callbacks with a generation that connect() and cleanUp() advance, so a close reported by a socket that was already replaced is ignored. Covered by a close reported by a replaced socket does not disturb the next connection in test/core/stale_socket_close_test.dart.

events.emit(EngineDisconnectedEvent(reason: reason));
}

void setRegionUrlProvider(RegionUrlProvider provider) {
Expand Down
43 changes: 34 additions & 9 deletions lib/src/core/room.dart
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {
final Engine engine;
// suppport for multiple event listeners
late final EventsListener<EngineEvent> _engineListener;

// The teardown disconnect() is running, shared by calls that overlap it.
Future<void>? _disconnectInFlight;
//
late EventsListener<SignalEvent> _signalListener;

Expand Down Expand Up @@ -695,6 +698,8 @@ class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {
notifyListeners();
})
..on<EngineDisconnectedEvent>((event) async {
// disconnect() tears down and reports the disconnect it started itself
if (_disconnectInFlight != null) return;
// Suppress while a full reconnect is either pending or running — the
// engine is going to re-establish the session, this is not a real
// disconnect. Both flags are needed since the attempt consumes the
Expand Down Expand Up @@ -823,18 +828,38 @@ class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {
}
});

/// Disconnects from the room, notifying server of disconnection.
Future<void> disconnect() async {
final bool isPendingReconnect = engine.isPendingReconnect;
if (engine.isClosed && !isPendingReconnect && engine.connectionState == ConnectionState.disconnected) {
/// Leaves the room. Sends a best effort Leave request and returns once the
/// engine and the room are torn down, without waiting on the server, so
/// connect() may be called again immediately. Calls that overlap share one
/// teardown.
Future<void> disconnect() {
final inFlight = _disconnectInFlight;
if (inFlight != null) return inFlight;
if (engine.isClosed && !engine.isPendingReconnect && engine.connectionState == ConnectionState.disconnected) {
logger.warning('Engine is already closed');
return;
return Future.value();
}
await engine.disconnect();
if (!isPendingReconnect) {
await _engineListener.waitFor<EngineDisconnectedEvent>(duration: const Duration(seconds: 10));
return _disconnectInFlight = _tearDown();
}

Future<void> _tearDown() async {
try {
// The room's own cleanup runs even when the engine teardown fails.
try {
await engine.disconnect();
} finally {
await _cleanUp();
}
} finally {
// Released before reporting, so a disconnect() made after a rejoin from
// this event gets a teardown of its own.
_disconnectInFlight = null;
// Reported once the room is torn down, also when a step failed, so a
// listener that connects again on this event cannot have its new
// session cleared by the teardown.
events.emit(RoomDisconnectedEvent(reason: DisconnectReason.clientInitiated));
notifyListeners();
}
await _cleanUp();
}

Future<void> setE2EEEnabled(bool enabled) async {
Expand Down
185 changes: 185 additions & 0 deletions test/core/disconnect_event_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,19 @@
@Timeout(Duration(seconds: 5))
library;

import 'dart:async';

import 'package:flutter_test/flutter_test.dart';

import 'package:livekit_client/livekit_client.dart';
import 'package:livekit_client/src/core/engine.dart';
import 'package:livekit_client/src/internal/events.dart';
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 'package:livekit_client/src/support/websocket.dart';
import 'package:livekit_client/src/types/internal.dart';
import '../mock/e2e_container.dart';
import '../mock/peerconnection_mock.dart';

const exampleUri = 'ws://www.example.com';
const token = 'token';
Expand Down Expand Up @@ -115,4 +121,183 @@ void main() {
expect(roomDisconnectedEvents, hasLength(1));
expect(roomDisconnectedEvents.single.reason, DisconnectReason.signalingConnectionFailure);
});

test('disconnect completes when the server closes the socket without echoing the leave', () async {
await container.connectRoom();
final disconnectedEvents = <RoomDisconnectedEvent>[];
container.room.events.on<RoomDisconnectedEvent>(disconnectedEvents.add);

final disconnecting = container.room.disconnect();
await Future<void>.delayed(const Duration(milliseconds: 10));
// media nodes drop queued leave messages on close, so only the close arrives
container.wsConnector.onDispose();

await disconnecting.timeout(const Duration(seconds: 2));
await Future<void>.delayed(const Duration(milliseconds: 50));

expect(container.room.connectionState, ConnectionState.disconnected);
expect(disconnectedEvents.map((e) => e.reason), [DisconnectReason.clientInitiated]);
expect(_leavesSent(container), 1);
});

test('disconnect with a leave echo followed by the socket close emits exactly one disconnected event', () async {
await container.connectRoom();
final disconnectedEvents = <RoomDisconnectedEvent>[];
container.room.events.on<RoomDisconnectedEvent>(disconnectedEvents.add);
final engineDisconnects = <EngineDisconnectedEvent>[];
final engineListener = container.engine.createListener()..on<EngineDisconnectedEvent>(engineDisconnects.add);

final disconnecting = container.room.disconnect();
await Future<void>.delayed(const Duration(milliseconds: 10));
container.wsConnector.onData(_leave(lk_rtc.LeaveRequest_Action.DISCONNECT));
await Future<void>.delayed(const Duration(milliseconds: 10));
// the real socket reports its close after the SDK disposed it
container.wsConnector.onDispose();

await disconnecting.timeout(const Duration(seconds: 2));
await Future<void>.delayed(const Duration(milliseconds: 50));
await engineListener.dispose();

expect(container.room.connectionState, ConnectionState.disconnected);
expect(disconnectedEvents, hasLength(1));
expect(engineDisconnects, hasLength(1));
expect(_leavesSent(container), 1);
});

test('disconnect returns with the room torn down, without waiting on the server', () async {
await container.connectRoom();
final disconnectedEvents = <RoomDisconnectedEvent>[];
container.room.events.on<RoomDisconnectedEvent>(disconnectedEvents.add);

// no leave echo, no socket close from the server, nothing at all
await container.room.disconnect().timeout(const Duration(seconds: 2));

expect(container.room.connectionState, ConnectionState.disconnected);
expect(container.engine.publisher, isNull);
expect(container.engine.subscriber, isNull);
expect(container.room.localParticipant, isNull);
expect(_leavesSent(container), 1);
await Future<void>.delayed(const Duration(milliseconds: 50));
expect(disconnectedEvents.map((e) => e.reason), [DisconnectReason.clientInitiated]);
});

test('overlapping disconnect calls share one teardown', () async {
await container.connectRoom();
final disconnectedEvents = <RoomDisconnectedEvent>[];
container.room.events.on<RoomDisconnectedEvent>(disconnectedEvents.add);

final first = container.room.disconnect();
final second = container.room.disconnect();
await Future.wait([first, second]).timeout(const Duration(seconds: 2));

// both callers come back only once the teardown is done
expect(container.room.localParticipant, isNull);
expect(container.room.connectionState, ConnectionState.disconnected);
await Future<void>.delayed(const Duration(milliseconds: 50));
expect(disconnectedEvents, hasLength(1));
expect(_leavesSent(container), 1);
});

test('connect again to the same room right after disconnect returns', () async {
// the case behind issue 553: cleanup from the first session racing the second connect
await container.connectRoom();
await container.room.disconnect();

final events = <RoomEvent>[];
container.room.events.on<RoomConnectedEvent>(events.add);
container.room.events.on<RoomDisconnectedEvent>(events.add);
await container.connectRoom();
await Future<void>.delayed(const Duration(milliseconds: 50));

expect(container.room.connectionState, ConnectionState.connected);
expect(container.room.localParticipant, isNotNull);
expect(events.whereType<RoomDisconnectedEvent>(), isEmpty, reason: 'no stale disconnect from the first session');
expect(events.whereType<RoomConnectedEvent>(), hasLength(1));

await container.room.disconnect().timeout(const Duration(seconds: 2));
expect(container.room.connectionState, ConnectionState.disconnected);
});

test('a connect started from the disconnected event survives the old teardown', () async {
// an app that rejoins as soon as it hears it was disconnected
await container.connectRoom();
var tornDownWhenReported = false;
final rejoin = Completer<Object?>();
final listener = container.room.createListener();
listener.once<RoomDisconnectedEvent>((_) {
// the event comes after the teardown, never in the middle of it
tornDownWhenReported = container.room.localParticipant == null && container.engine.publisher == null;
rejoin.complete(container.connectRoom().then<Object?>((_) => null, onError: (Object e) => e));
});

await container.room.disconnect();
final rejoinError = await rejoin.future.timeout(
const Duration(seconds: 2),
onTimeout: () => fail('the disconnected event must reach the app'),
);
expect(tornDownWhenReported, isTrue);
expect(rejoinError, isNull, reason: 'the rejoin must not fail');
await Future<void>.delayed(const Duration(milliseconds: 50));

expect(container.room.connectionState, ConnectionState.connected);
expect(container.room.localParticipant, isNotNull);

// and the rejoined session tears down on its own disconnect
await container.room.disconnect().timeout(const Duration(seconds: 2));
expect(container.room.connectionState, ConnectionState.disconnected);
expect(container.room.localParticipant, isNull);
await listener.dispose();
});

test('a failing teardown step still reports the disconnect and tears down the rest', () async {
final failing = E2EContainer(
createEngine: (client, roomOptions) => _CleanUpFailsEngine(
connectOptions: const ConnectOptions(),
roomOptions: roomOptions,
signalClient: client,
peerConnectionCreate: MockPeerConnection.create,
),
);
final engine = failing.engine as _CleanUpFailsEngine;
try {
await failing.connectRoom();
final disconnectedEvents = <RoomDisconnectedEvent>[];
failing.room.events.on<RoomDisconnectedEvent>(disconnectedEvents.add);

engine.failCleanUp = true;
await expectLater(failing.room.disconnect(), throwsA(isA<StateError>()));
await Future<void>.delayed(const Duration(milliseconds: 50));

expect(disconnectedEvents.map((e) => e.reason), [DisconnectReason.clientInitiated]);
expect(failing.room.localParticipant, isNull, reason: "the room's cleanup runs after the engine's failed");
} finally {
engine.failCleanUp = false;
await failing.dispose();
}
});
}

List<int> _leave(lk_rtc.LeaveRequest_Action action) => lk_rtc.SignalResponse(
leave: lk_rtc.LeaveRequest(action: action, reason: lk_models.DisconnectReason.CLIENT_INITIATED),
).writeToBuffer();

/// How many Leave requests the SDK sent over any socket.
int _leavesSent(E2EContainer container) =>
container.wsConnector.sentData.where((data) => lk_rtc.SignalRequest.fromBuffer(data).hasLeave()).length;

class _CleanUpFailsEngine extends Engine {
_CleanUpFailsEngine({
required super.connectOptions,
required super.roomOptions,
super.signalClient,
super.peerConnectionCreate,
});

bool failCleanUp = false;

@override
Future<void> cleanUp() async {
await super.cleanUp();
if (failCleanUp) throw StateError('engine cleanUp failed');
}
}
21 changes: 14 additions & 7 deletions test/mock/e2e_container.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,22 @@ class E2EContainer {
/// since [connectRoom] returned. Populated only when [captureOutbound] is true.
final List<lk_models.DataPacket> capturedDataPackets = [];

E2EContainer({RoomOptions roomOptions = const RoomOptions()}) {
/// [createEngine] swaps in an engine of the test's own, for example one
/// whose teardown fails.
E2EContainer({
RoomOptions roomOptions = const RoomOptions(),
Engine Function(SignalClient client, RoomOptions roomOptions)? createEngine,
}) {
wsConnector = MockWebSocketConnector();
client = SignalClient(wsConnector.connect);
engine = Engine(
connectOptions: const ConnectOptions(),
roomOptions: roomOptions,
signalClient: client,
peerConnectionCreate: MockPeerConnection.create,
);
engine =
createEngine?.call(client, roomOptions) ??
Engine(
connectOptions: const ConnectOptions(),
roomOptions: roomOptions,
signalClient: client,
peerConnectionCreate: MockPeerConnection.create,
);
room = Room(engine: engine);
}

Expand Down
Loading