diff --git a/.changes/disconnect-completes-on-socket-close b/.changes/disconnect-completes-on-socket-close new file mode 100644 index 000000000..00ab36953 --- /dev/null +++ b/.changes/disconnect-completes-on-socket-close @@ -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" \ No newline at end of file diff --git a/lib/src/core/engine.dart b/lib/src/core/engine.dart index 48c9d227f..0fd4200ed 100644 --- a/lib/src/core/engine.dart +++ b/lib/src/core/engine.dart @@ -1647,6 +1647,8 @@ class Engine extends Disposable with EventsEmittable { }) ..on((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, @@ -1736,6 +1738,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()); @@ -1767,17 +1775,19 @@ class Engine extends Disposable with EventsEmittable { }) 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(); + events.emit(EngineDisconnectedEvent(reason: reason)); } void setRegionUrlProvider(RegionUrlProvider provider) { diff --git a/lib/src/core/room.dart b/lib/src/core/room.dart index 5731309e1..74e4a1b74 100644 --- a/lib/src/core/room.dart +++ b/lib/src/core/room.dart @@ -129,6 +129,9 @@ class Room extends DisposableChangeNotifier with EventsEmittable { final Engine engine; // suppport for multiple event listeners late final EventsListener _engineListener; + + // The teardown disconnect() is running, shared by calls that overlap it. + Future? _disconnectInFlight; // late EventsListener _signalListener; @@ -695,6 +698,8 @@ class Room extends DisposableChangeNotifier with EventsEmittable { notifyListeners(); }) ..on((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 @@ -823,18 +828,38 @@ class Room extends DisposableChangeNotifier with EventsEmittable { } }); - /// Disconnects from the room, notifying server of disconnection. - Future 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 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(duration: const Duration(seconds: 10)); + return _disconnectInFlight = _tearDown(); + } + + Future _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 setE2EEEnabled(bool enabled) async { diff --git a/test/core/disconnect_event_test.dart b/test/core/disconnect_event_test.dart index 3864b2f43..d26ed2ef0 100644 --- a/test/core/disconnect_event_test.dart +++ b/test/core/disconnect_event_test.dart @@ -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'; @@ -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 = []; + 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]); + 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(_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 { + 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); + 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(); + 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); + }); + + 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(); + final listener = container.room.createListener(); + listener.once((_) { + // 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 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); }