From fb7958a52e81f4902d262c3d8ea04273e13e662a Mon Sep 17 00:00:00 2001 From: Gianluca Boiano Date: Sun, 13 Sep 2026 15:33:44 +0200 Subject: [PATCH] Serialize connects against the connector-level teardown Fourth review round: - UsbSerialService.connect() now waits for _activeDisconnect before it claims the `connecting` status, covering the Android USB-host path too; previously the wait sat inside the desktop branch, so an Android reconnect could still be overwritten by the old teardown. - MeshCoreConnector.disconnect() is now a re-entrant-safe wrapper around _disconnectInternal() that publishes the teardown as _activeDisconnect, and connect()/connectUsb()/connectTcp() join it before starting. The transport-level guard alone could not prevent the connector's own teardown tail from setting the state back to `disconnected` after a new connection was up. Repeat disconnect() calls now join the in-flight teardown instead of returning early while it is still running. flutter analyze clean; flutter test 570 passing, 2 pre-existing failures in message_url_image_helper_test.dart (identical on a stashed tree); flutter build linux --debug succeeds. --- lib/connector/meshcore_connector.dart | 47 ++++++++++++++++++++- lib/services/usb_serial_service_native.dart | 39 +++++++++-------- 2 files changed, 67 insertions(+), 19 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 37198761..25046783 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -188,6 +188,12 @@ class MeshCoreConnector extends ChangeNotifier { String? _lastDeviceId; String? _lastDeviceDisplayName; bool _manualDisconnect = false; + /// Non-null while [disconnect] is tearing the transport down. Connect paths + /// join it so a teardown cannot finish after a new connection and reset the + /// state to `disconnected`. USB made this reachable: its native close now + /// waits out the kernel's closing_wait off the UI isolate, so the teardown + /// can outlive the tap that starts the next connection. + Future? _activeDisconnect; final MeshCoreUsbManager _usbManager = MeshCoreUsbManager(); final LinuxBlePairingService _linuxBlePairingService = LinuxBlePairingService(); @@ -1763,6 +1769,8 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'USB', ); + await _awaitActiveDisconnect(); + await stopScan(); _cancelReconnectTimer(); _manualDisconnect = false; @@ -1860,6 +1868,8 @@ class MeshCoreConnector extends ChangeNotifier { _appDebugLogService?.info('connectTcp: endpoint=$host:$port', tag: 'TCP'); + await _awaitActiveDisconnect(); + await stopScan(); _cancelReconnectTimer(); _manualDisconnect = false; @@ -2008,6 +2018,8 @@ class MeshCoreConnector extends ChangeNotifier { return; } + await _awaitActiveDisconnect(); + _activeTransport = MeshCoreTransportType.bluetooth; await stopScan(); @@ -2747,8 +2759,41 @@ class MeshCoreConnector extends ChangeNotifier { Future disconnect({ bool manual = true, bool skipBleDeviceDisconnect = false, + }) { + final inFlight = _activeDisconnect; + if (inFlight != null) return inFlight; + final teardown = _disconnectInternal( + manual: manual, + skipBleDeviceDisconnect: skipBleDeviceDisconnect, + ); + _activeDisconnect = teardown; + return teardown.whenComplete(() { + if (identical(_activeDisconnect, teardown)) { + _activeDisconnect = null; + } + }); + } + + /// Joins an in-flight [disconnect] so a new connection cannot be started + /// while the previous teardown is still running. + Future _awaitActiveDisconnect() async { + final pending = _activeDisconnect; + if (pending == null) return; + _appDebugLogService?.info( + 'Waiting for the in-flight disconnect to finish before connecting', + tag: 'Connection', + ); + try { + await pending; + } catch (_) { + // Teardown failures are logged by the disconnect path. + } + } + + Future _disconnectInternal({ + required bool manual, + required bool skipBleDeviceDisconnect, }) async { - if (_state == MeshCoreConnectionState.disconnecting) return; final transportAtDisconnect = _activeTransport; final transportLabel = switch (transportAtDisconnect) { MeshCoreTransportType.bluetooth => 'BLE', diff --git a/lib/services/usb_serial_service_native.dart b/lib/services/usb_serial_service_native.dart index 2a0e7526..781dfcb9 100644 --- a/lib/services/usb_serial_service_native.dart +++ b/lib/services/usb_serial_service_native.dart @@ -126,6 +126,26 @@ class UsbSerialService { throw UnsupportedError('USB serial is not supported on this platform.'); } + // A previous disconnect may still be running: on desktop its native close + // waits out the kernel's closing_wait in a helper isolate, and the + // teardown only marks the transport disconnected afterwards. Reopening + // before it finishes would let the old teardown overwrite the new + // connection's state (and, on desktop, race fl_free()/fl_close() over the + // process-global flserial_tab). Wait for the whole teardown — on every + // platform — before claiming the `connecting` state. + final pendingDisconnect = _activeDisconnect; + if (pendingDisconnect != null) { + _debugLogService?.info( + 'Waiting for the previous USB disconnect to finish before reopening', + tag: 'USB Serial', + ); + try { + await pendingDisconnect; + } catch (_) { + // Failures are already logged by the teardown path. + } + } + _status = UsbSerialStatus.connecting; var normalizedPortName = normalizeUsbPortName(portName); _frameDecoder.reset(); @@ -163,24 +183,7 @@ class UsbSerialService { // // This must happen before we register any new NativeCallable, so it must // be the very first thing we do in the desktop branch. - // A previous disconnect may still be running: its native close waits out - // the kernel's closing_wait in a helper isolate, and it only marks the - // transport disconnected afterwards. fl_close() and fl_free() mutate the - // same process-global flserial_tab, so reopening now could race the - // helper, and the old teardown could later overwrite the new connection - // state. Wait for the whole teardown, not just the native close. - final pendingDisconnect = _activeDisconnect; - if (pendingDisconnect != null) { - _debugLogService?.info( - 'Waiting for the previous USB disconnect to finish before reopening', - tag: 'USB Serial', - ); - try { - await pendingDisconnect; - } catch (_) { - // Failures are already logged by the teardown path. - } - } + // (the previous teardown was already awaited above) try { bindings.fl_free();