From f47c649a951e0090de863cb38ed983f6c2a026c0 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Wed, 16 Sep 2026 00:13:48 +0800 Subject: [PATCH 1/4] fix: complete disconnect() when the server closes the socket without echoing the leave engine.disconnect() sends the Leave and relies on the server's echo to run cleanup and emit EngineDisconnectedEvent. Media nodes drop queued leave messages when they close the signal sink, so the echo can be lost. The socket close was then ignored because _isClosed was set, and Room.disconnect() waited out its 10 s timeout for an event that never came, leaving the room half torn down. The engine now remembers a disconnect that is waiting for its echo and, on a socket close in that window, runs cleanup and emits the event itself. A close that follows the echo is still ignored, so there is no second event. --- .changes/disconnect-completes-on-socket-close | 1 + lib/src/core/engine.dart | 32 ++++++++++--- test/core/disconnect_event_test.dart | 45 +++++++++++++++++++ 3 files changed, 73 insertions(+), 5 deletions(-) create mode 100644 .changes/disconnect-completes-on-socket-close diff --git a/.changes/disconnect-completes-on-socket-close b/.changes/disconnect-completes-on-socket-close new file mode 100644 index 000000000..51e8ca92b --- /dev/null +++ b/.changes/disconnect-completes-on-socket-close @@ -0,0 +1 @@ +patch type="fixed" "disconnect() completes when the server closes the signal connection without echoing the leave, instead of timing out after 10 s" \ No newline at end of file diff --git a/lib/src/core/engine.dart b/lib/src/core/engine.dart index ba82dfefb..8b98d5de6 100644 --- a/lib/src/core/engine.dart +++ b/lib/src/core/engine.dart @@ -137,6 +137,10 @@ class Engine extends Disposable with EventsEmittable { bool _isClosed = false; + // Reason of a disconnect() that has sent its Leave and is waiting for the + // server to answer. Non-null only during that window. + DisconnectReason? _pendingDisconnect; + bool get isClosed => _isClosed; bool get isPendingReconnect => _reconnectStart != null && _reconnectTimeout != null; @@ -249,6 +253,7 @@ class Engine extends Disposable with EventsEmittable { //reset state _isClosed = false; + _pendingDisconnect = null; try { // wait for socket to connect rtc server @@ -1512,11 +1517,24 @@ class Engine extends Disposable with EventsEmittable { }) ..on((event) async { logger.fine('Signal disconnected ${event.reason}'); - if (event.reason == DisconnectReason.disconnected && !_isClosed) { - await handleReconnect( - ClientDisconnectReason.signal, - reconnectReason: lk_models.ReconnectReason.RR_SIGNAL_DISCONNECTED, - ); + if (event.reason == DisconnectReason.disconnected) { + if (!_isClosed) { + await handleReconnect( + ClientDisconnectReason.signal, + reconnectReason: lk_models.ReconnectReason.RR_SIGNAL_DISCONNECTED, + ); + } else if (_pendingDisconnect != null) { + // disconnect() sent its Leave and the server closed the socket + // without echoing it. Media nodes drop queued leave messages on + // close, so the close itself is how this disconnect completes. + // Otherwise Room.disconnect() waits out its timeout for an event + // that never comes. + final reason = _pendingDisconnect!; + _pendingDisconnect = null; + logger.fine('signal closed during disconnect, completing without the leave echo'); + await cleanUp(); + events.emit(EngineDisconnectedEvent(reason: reason)); + } } // signalingConnectionFailure is intentionally not relayed as // EngineDisconnectedEvent here. The signal client emits it while the @@ -1622,6 +1640,9 @@ class Engine extends Disposable with EventsEmittable { _isClosed = true; events.emit(EngineClosingEvent()); if (connectionState == ConnectionState.connected) { + // the server answers with a Leave, whose handler calls back into + // disconnect() on the path below and emits the event + _pendingDisconnect = reason; await signalClient.sendLeave(); } else { if (isPendingReconnect) { @@ -1630,6 +1651,7 @@ class Engine extends Disposable with EventsEmittable { await _signalListener.cancelAll(); _clearPendingReconnect(); } + _pendingDisconnect = null; await cleanUp(); events.emit(EngineDisconnectedEvent(reason: reason)); } diff --git a/test/core/disconnect_event_test.dart b/test/core/disconnect_event_test.dart index 3864b2f43..412dbab6f 100644 --- a/test/core/disconnect_event_test.dart +++ b/test/core/disconnect_event_test.dart @@ -19,6 +19,8 @@ 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/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'; @@ -115,4 +117,47 @@ 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 = []; + container.room.events.on(disconnectedEvents.add); + + final disconnecting = container.room.disconnect(); + await Future.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.delayed(const Duration(milliseconds: 50)); + + expect(container.room.connectionState, ConnectionState.disconnected); + expect(disconnectedEvents.map((e) => e.reason), [DisconnectReason.clientInitiated]); + }); + + test('disconnect with a leave echo followed by the socket close emits exactly one disconnected event', () async { + await container.connectRoom(); + final disconnectedEvents = []; + container.room.events.on(disconnectedEvents.add); + + final disconnecting = container.room.disconnect(); + await Future.delayed(const Duration(milliseconds: 10)); + container.wsConnector.onData( + lk_rtc.SignalResponse( + leave: lk_rtc.LeaveRequest( + action: lk_rtc.LeaveRequest_Action.DISCONNECT, + reason: lk_models.DisconnectReason.CLIENT_INITIATED, + ), + ).writeToBuffer(), + ); + await Future.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.delayed(const Duration(milliseconds: 50)); + + expect(container.room.connectionState, ConnectionState.disconnected); + expect(disconnectedEvents, hasLength(1)); + }); } From 645baaf8e0bbf7f6e0a405209fd2abf311edec53 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Wed, 16 Sep 2026 01:31:22 +0800 Subject: [PATCH 2/4] fix: disconnect() tears down locally after sending the Leave instead of waiting for the echo The engine used to send the Leave and rely on the server's echo to run cleanup and emit EngineDisconnectedEvent, and Room.disconnect() waited up to 10 s for that event. Media nodes drop queued leave messages when they close the signal sink, so the echo can be lost, and every lost echo was a 10 s stall, a TimeoutException, and a room left half torn down. No other SDK waits on the server here. disconnect() now sends the Leave, runs cleanUp() and emits the event in one go, like JS, Swift, Android and Rust. A Leave that arrives after disconnect() started is the echo and is ignored. Room.disconnect() owns the teardown for the disconnect it started, so the engine event handler skips its own cleanup in that case and a connect() right after disconnect() returns cannot race it. Replaces the earlier socket close fallback on this branch. --- .changes/disconnect-completes-on-socket-close | 2 +- lib/src/core/engine.dart | 59 ++++++++----------- lib/src/core/room.dart | 25 +++++--- test/core/disconnect_event_test.dart | 36 +++++++++++ 4 files changed, 78 insertions(+), 44 deletions(-) diff --git a/.changes/disconnect-completes-on-socket-close b/.changes/disconnect-completes-on-socket-close index 51e8ca92b..6a9a2eb00 100644 --- a/.changes/disconnect-completes-on-socket-close +++ b/.changes/disconnect-completes-on-socket-close @@ -1 +1 @@ -patch type="fixed" "disconnect() completes when the server closes the signal connection without echoing the leave, instead of timing out after 10 s" \ No newline at end of file +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" \ No newline at end of file diff --git a/lib/src/core/engine.dart b/lib/src/core/engine.dart index 8b98d5de6..aff7e34fc 100644 --- a/lib/src/core/engine.dart +++ b/lib/src/core/engine.dart @@ -137,10 +137,6 @@ class Engine extends Disposable with EventsEmittable { bool _isClosed = false; - // Reason of a disconnect() that has sent its Leave and is waiting for the - // server to answer. Non-null only during that window. - DisconnectReason? _pendingDisconnect; - bool get isClosed => _isClosed; bool get isPendingReconnect => _reconnectStart != null && _reconnectTimeout != null; @@ -253,7 +249,6 @@ class Engine extends Disposable with EventsEmittable { //reset state _isClosed = false; - _pendingDisconnect = null; try { // wait for socket to connect rtc server @@ -1517,24 +1512,12 @@ class Engine extends Disposable with EventsEmittable { }) ..on((event) async { logger.fine('Signal disconnected ${event.reason}'); - if (event.reason == DisconnectReason.disconnected) { - if (!_isClosed) { - await handleReconnect( - ClientDisconnectReason.signal, - reconnectReason: lk_models.ReconnectReason.RR_SIGNAL_DISCONNECTED, - ); - } else if (_pendingDisconnect != null) { - // disconnect() sent its Leave and the server closed the socket - // without echoing it. Media nodes drop queued leave messages on - // close, so the close itself is how this disconnect completes. - // Otherwise Room.disconnect() waits out its timeout for an event - // that never comes. - final reason = _pendingDisconnect!; - _pendingDisconnect = null; - logger.fine('signal closed during disconnect, completing without the leave echo'); - await cleanUp(); - events.emit(EngineDisconnectedEvent(reason: reason)); - } + // after disconnect() the close is ours, cleanUp() already ran + if (event.reason == DisconnectReason.disconnected && !_isClosed) { + await handleReconnect( + ClientDisconnectReason.signal, + reconnectReason: lk_models.ReconnectReason.RR_SIGNAL_DISCONNECTED, + ); } // signalingConnectionFailure is intentionally not relayed as // EngineDisconnectedEvent here. The signal client emits it while the @@ -1618,6 +1601,12 @@ class Engine extends Disposable with EventsEmittable { 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()); @@ -1640,21 +1629,19 @@ class Engine extends Disposable with EventsEmittable { _isClosed = true; events.emit(EngineClosingEvent()); if (connectionState == ConnectionState.connected) { - // the server answers with a Leave, whose handler calls back into - // disconnect() on the path below and emits the event - _pendingDisconnect = reason; + // 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(); - } - _pendingDisconnect = null; - 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(); + events.emit(EngineDisconnectedEvent(reason: reason)); } void setRegionUrlProvider(RegionUrlProvider provider) { diff --git a/lib/src/core/room.dart b/lib/src/core/room.dart index 4ef28bbf0..7e30d983c 100644 --- a/lib/src/core/room.dart +++ b/lib/src/core/room.dart @@ -124,6 +124,9 @@ class Room extends DisposableChangeNotifier with EventsEmittable { final Engine engine; // suppport for multiple event listeners late final EventsListener _engineListener; + + // true while disconnect() is tearing the room down itself + bool _disconnecting = false; // late EventsListener _signalListener; @@ -655,7 +658,11 @@ class Room extends DisposableChangeNotifier with EventsEmittable { // pending one when it starts. if ((!engine.fullReconnectOnNext && !engine.isFullReconnectInProgress) || event.reason == DisconnectReason.clientInitiated) { - await _cleanUp(disposeLocalParticipant: false); + // disconnect() owns the teardown for the disconnect it started, so a + // connect() right after it returns cannot race this handler + if (!_disconnecting) { + await _cleanUp(disposeLocalParticipant: false); + } events.emit(RoomDisconnectedEvent(reason: event.reason)); notifyListeners(); } @@ -761,17 +768,21 @@ class Room extends DisposableChangeNotifier with EventsEmittable { }); /// Disconnects from the room, notifying server of disconnection. + /// Leaves the room. Returns once the engine and the room are torn down, so + /// connect() may be called again immediately. Nothing here waits on the + /// server, the Leave request is best effort. Future disconnect() async { - final bool isPendingReconnect = engine.isPendingReconnect; - if (engine.isClosed && !isPendingReconnect && engine.connectionState == ConnectionState.disconnected) { + if (engine.isClosed && !engine.isPendingReconnect && engine.connectionState == ConnectionState.disconnected) { logger.warning('Engine is already closed'); return; } - await engine.disconnect(); - if (!isPendingReconnect) { - await _engineListener.waitFor(duration: const Duration(seconds: 10)); + _disconnecting = true; + try { + await engine.disconnect(); + await _cleanUp(); + } finally { + _disconnecting = false; } - await _cleanUp(); } Future setE2EEEnabled(bool enabled) async { diff --git a/test/core/disconnect_event_test.dart b/test/core/disconnect_event_test.dart index 412dbab6f..bc0694b27 100644 --- a/test/core/disconnect_event_test.dart +++ b/test/core/disconnect_event_test.dart @@ -160,4 +160,40 @@ void main() { expect(container.room.connectionState, ConnectionState.disconnected); expect(disconnectedEvents, hasLength(1)); }); + + test('disconnect returns with the room torn down, without waiting on the server', () async { + await container.connectRoom(); + final disconnectedEvents = []; + container.room.events.on(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); + await Future.delayed(const Duration(milliseconds: 50)); + expect(disconnectedEvents.map((e) => e.reason), [DisconnectReason.clientInitiated]); + }); + + 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 = []; + container.room.events.on(events.add); + container.room.events.on(events.add); + await container.connectRoom(); + await Future.delayed(const Duration(milliseconds: 50)); + + expect(container.room.connectionState, ConnectionState.connected); + expect(container.room.localParticipant, isNotNull); + expect(events.whereType(), isEmpty, reason: 'no stale disconnect from the first session'); + expect(events.whereType(), hasLength(1)); + + await container.room.disconnect().timeout(const Duration(seconds: 2)); + expect(container.room.connectionState, ConnectionState.disconnected); + }); } From 3f6510d2dbbb0c30f85363008efd626d099d3aa3 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Sat, 17 Oct 2026 05:45:53 +0800 Subject: [PATCH 3/4] fix: report a client disconnect only once the room is torn down disconnect() let the engine handler emit RoomDisconnectedEvent as soon as the engine had closed, while the room's own teardown was still running. An app that connects again from that event started its new session in the middle of the old teardown, which then disposed the new engine state and left the room disconnected. The handler now leaves the disconnect it did not start alone, and disconnect() emits the event after _cleanUp() has finished. --- lib/src/core/room.dart | 12 +++++++----- test/core/disconnect_event_test.dart | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/lib/src/core/room.dart b/lib/src/core/room.dart index 7e30d983c..665870eca 100644 --- a/lib/src/core/room.dart +++ b/lib/src/core/room.dart @@ -652,17 +652,15 @@ class Room extends DisposableChangeNotifier with EventsEmittable { notifyListeners(); }) ..on((event) async { + // disconnect() tears down and reports the disconnect it started itself + if (_disconnecting) 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 // pending one when it starts. if ((!engine.fullReconnectOnNext && !engine.isFullReconnectInProgress) || event.reason == DisconnectReason.clientInitiated) { - // disconnect() owns the teardown for the disconnect it started, so a - // connect() right after it returns cannot race this handler - if (!_disconnecting) { - await _cleanUp(disposeLocalParticipant: false); - } + await _cleanUp(disposeLocalParticipant: false); events.emit(RoomDisconnectedEvent(reason: event.reason)); notifyListeners(); } @@ -783,6 +781,10 @@ class Room extends DisposableChangeNotifier with EventsEmittable { } finally { _disconnecting = false; } + // Reported only once the room is torn down, 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(); } Future setE2EEEnabled(bool enabled) async { diff --git a/test/core/disconnect_event_test.dart b/test/core/disconnect_event_test.dart index bc0694b27..695736cc5 100644 --- a/test/core/disconnect_event_test.dart +++ b/test/core/disconnect_event_test.dart @@ -196,4 +196,27 @@ void main() { 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(); + Future? rejoin; + final listener = container.room.createListener(); + listener.once((_) { + rejoin = container.connectRoom().then((_) => null, onError: (Object e) => e); + }); + + await container.room.disconnect(); + final deadline = DateTime.now().add(const Duration(seconds: 2)); + while (rejoin == null && DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 5)); + } + expect(rejoin, isNotNull, reason: 'the disconnected event must reach the app'); + expect(await rejoin, isNull, reason: 'the rejoin must not fail'); + await Future.delayed(const Duration(milliseconds: 50)); + + expect(container.room.connectionState, ConnectionState.connected); + expect(container.room.localParticipant, isNotNull); + await listener.dispose(); + }); } From 25bb462af565908fbefbcc61e58aea81186b98b8 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Sat, 21 Nov 2026 00:39:43 +0800 Subject: [PATCH 4/4] fix: share one teardown between overlapping disconnect() calls, and report it when a step fails Two disconnect() calls that overlapped both passed the closed check, so each sent a Leave, ran the teardown and emitted RoomDisconnectedEvent. They now share the teardown in flight, released before the event so a rejoin from that event gets a teardown of its own on its next disconnect(). A teardown step that threw skipped the room's cleanup or the only RoomDisconnectedEvent, because the engine event handler stays quiet while disconnect() runs. The room's cleanup now runs after a failed engine teardown, the event is emitted either way, and the error still reaches the caller. The tests now check that the Leave is sent, count engine events in the echo case, and check that the room is torn down when the disconnected event arrives. Found in review (Codex). --- .changes/disconnect-completes-on-socket-close | 2 +- lib/src/core/engine.dart | 3 +- lib/src/core/room.dart | 46 ++++--- test/core/disconnect_event_test.dart | 113 +++++++++++++++--- test/mock/e2e_container.dart | 21 ++-- 5 files changed, 143 insertions(+), 42 deletions(-) diff --git a/.changes/disconnect-completes-on-socket-close b/.changes/disconnect-completes-on-socket-close index 6a9a2eb00..00ab36953 100644 --- a/.changes/disconnect-completes-on-socket-close +++ b/.changes/disconnect-completes-on-socket-close @@ -1 +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" \ No newline at end of file +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" \ No newline at end of file diff --git a/lib/src/core/engine.dart b/lib/src/core/engine.dart index e7c8b124c..0fd4200ed 100644 --- a/lib/src/core/engine.dart +++ b/lib/src/core/engine.dart @@ -1647,7 +1647,8 @@ class Engine extends Disposable with EventsEmittable { }) ..on((event) async { logger.fine('Signal disconnected ${event.reason}'); - // after disconnect() the close is ours, cleanUp() already ran + // 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, diff --git a/lib/src/core/room.dart b/lib/src/core/room.dart index ac0371d51..74e4a1b74 100644 --- a/lib/src/core/room.dart +++ b/lib/src/core/room.dart @@ -130,8 +130,8 @@ class Room extends DisposableChangeNotifier with EventsEmittable { // suppport for multiple event listeners late final EventsListener _engineListener; - // true while disconnect() is tearing the room down itself - bool _disconnecting = false; + // The teardown disconnect() is running, shared by calls that overlap it. + Future? _disconnectInFlight; // late EventsListener _signalListener; @@ -699,7 +699,7 @@ class Room extends DisposableChangeNotifier with EventsEmittable { }) ..on((event) async { // disconnect() tears down and reports the disconnect it started itself - if (_disconnecting) return; + 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 @@ -828,26 +828,38 @@ class Room extends DisposableChangeNotifier with EventsEmittable { } }); - /// Disconnects from the room, notifying server of disconnection. - /// Leaves the room. Returns once the engine and the room are torn down, so - /// connect() may be called again immediately. Nothing here waits on the - /// server, the Leave request is best effort. - Future disconnect() async { + /// 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 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(); } - _disconnecting = true; + return _disconnectInFlight = _tearDown(); + } + + Future _tearDown() async { try { - await engine.disconnect(); - await _cleanUp(); + // The room's own cleanup runs even when the engine teardown fails. + try { + await engine.disconnect(); + } finally { + await _cleanUp(); + } } finally { - _disconnecting = false; + // 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(); } - // Reported only once the room is torn down, 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(); } Future setE2EEEnabled(bool enabled) async { diff --git a/test/core/disconnect_event_test.dart b/test/core/disconnect_event_test.dart index 695736cc5..d26ed2ef0 100644 --- a/test/core/disconnect_event_test.dart +++ b/test/core/disconnect_event_test.dart @@ -15,15 +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'; @@ -133,32 +137,31 @@ void main() { 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 = []; container.room.events.on(disconnectedEvents.add); + final engineDisconnects = []; + final engineListener = container.engine.createListener()..on(engineDisconnects.add); final disconnecting = container.room.disconnect(); await Future.delayed(const Duration(milliseconds: 10)); - container.wsConnector.onData( - lk_rtc.SignalResponse( - leave: lk_rtc.LeaveRequest( - action: lk_rtc.LeaveRequest_Action.DISCONNECT, - reason: lk_models.DisconnectReason.CLIENT_INITIATED, - ), - ).writeToBuffer(), - ); + container.wsConnector.onData(_leave(lk_rtc.LeaveRequest_Action.DISCONNECT)); await Future.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.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 { @@ -173,10 +176,28 @@ void main() { expect(container.engine.publisher, isNull); expect(container.engine.subscriber, isNull); expect(container.room.localParticipant, isNull); + expect(_leavesSent(container), 1); await Future.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 = []; + container.room.events.on(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.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(); @@ -200,23 +221,83 @@ void main() { 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(); - Future? rejoin; + var tornDownWhenReported = false; + final rejoin = Completer(); final listener = container.room.createListener(); listener.once((_) { - rejoin = container.connectRoom().then((_) => null, onError: (Object e) => e); + // 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((_) => null, onError: (Object e) => e)); }); await container.room.disconnect(); - final deadline = DateTime.now().add(const Duration(seconds: 2)); - while (rejoin == null && DateTime.now().isBefore(deadline)) { - await Future.delayed(const Duration(milliseconds: 5)); - } - expect(rejoin, isNotNull, reason: 'the disconnected event must reach the app'); - expect(await rejoin, isNull, reason: 'the rejoin must not fail'); + 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.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 = []; + failing.room.events.on(disconnectedEvents.add); + + engine.failCleanUp = true; + await expectLater(failing.room.disconnect(), throwsA(isA())); + await Future.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 _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 cleanUp() async { + await super.cleanUp(); + if (failCleanUp) throw StateError('engine cleanUp failed'); + } } diff --git a/test/mock/e2e_container.dart b/test/mock/e2e_container.dart index 5a9965ae5..5a8e0ab41 100644 --- a/test/mock/e2e_container.dart +++ b/test/mock/e2e_container.dart @@ -38,15 +38,22 @@ class E2EContainer { /// since [connectRoom] returned. Populated only when [captureOutbound] is true. final List 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); }