From de758b5dfa3a0445df9b9ed2f6b2479dea68f644 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Fri, 21 Aug 2026 17:42:28 +0200 Subject: [PATCH] Final fixes --- lib/core/network/network_provider.dart | 24 ++++++++-- lib/core/widgets/app_bar.dart | 49 +++++++++++--------- lib/core/widgets/sync_status_dialog.dart | 4 +- lib/powersync/sync_watchdog.dart | 18 ++++--- test/core/network/network_provider_test.dart | 32 +++++++++++-- test/core/widgets/app_bar_test.dart | 18 ++++++- test/powersync/sync_watchdog_test.dart | 39 +++++++++++++++- 7 files changed, 141 insertions(+), 43 deletions(-) diff --git a/lib/core/network/network_provider.dart b/lib/core/network/network_provider.dart index 76584a8e0..5b00041ab 100644 --- a/lib/core/network/network_provider.dart +++ b/lib/core/network/network_provider.dart @@ -19,6 +19,7 @@ import 'dart:async'; import 'dart:io'; +import 'package:collection/collection.dart'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:flutter/widgets.dart'; import 'package:http/http.dart' as http; @@ -135,6 +136,11 @@ class ConnectivityState extends _$ConnectivityState { } void _update(List conn) { + // Same content is no change: the seed in particular usually re-delivers + // the optimistic default and must not trigger a second startup probe. + if (const ListEquality().equals(conn, state)) { + return; + } if (hasNetworkAdapter(conn) != hasNetworkAdapter(state)) { _logger.info('Network adapter ${hasNetworkAdapter(conn) ? 'available' : 'gone'}'); } @@ -190,9 +196,7 @@ class NetworkStatus extends _$NetworkStatus { // Listening on the raw list, not the derived adapter bool: an interface // switch (wifi to mobile) keeps the bool true but still warrants a probe. - ref.listen(connectivityStateProvider, (_, conn) { - unawaited(_probeRun(() => _update(conn, optimistic: true))); - }); + ref.listen(connectivityStateProvider, (_, _) => unawaited(_recheckOnChange())); // A stale offline state from the background shouldn't stick until the // next timer tick, so re-check optimistically on resume. @@ -250,6 +254,20 @@ class NetworkStatus extends _$NetworkStatus { return _inFlight ??= run().whenComplete(() => _inFlight = null); } + /// A connectivity change must never coalesce away: a pass already in + /// flight measured the old interface, so wait it out and run a fresh pass + /// on the new state. + Future _recheckOnChange() async { + if (_inFlight case final pending?) { + try { + await pending; + } catch (_) { + // The joined pass owns its error; this one only waits its turn. + } + } + await check(optimistic: true); + } + /// Schedules the next probe: the idle cadence while things work, one of the /// shorter [_probeRetryDelays] while they don't. Connectivity events only /// fire on adapter changes, so a dead backend needs an active probe. diff --git a/lib/core/widgets/app_bar.dart b/lib/core/widgets/app_bar.dart index 2b3ea6e04..ce63c5883 100644 --- a/lib/core/widgets/app_bar.dart +++ b/lib/core/widgets/app_bar.dart @@ -62,30 +62,37 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { icon: Icon(status.icon), onPressed: () => showDialog( context: context, - // The dialog watches the sync state itself; only the server URL is - // a snapshot taken when it opens. The reconnect action is never - // gated on the network status: it exists for the case where that - // status is wrong, so it re-probes instead of trusting it + // The dialog watches the sync state itself; only the server URL + // and the adapter gate are snapshots taken when it opens. The + // reconnect action is never gated on the reachability status (it + // exists for when that status is wrong), but the adapter is a + // platform fact: without one there is no transport to retry on. builder: (_) => SyncStatusDialog( serverUrl: ref.read(wgerBaseProvider).serverUrl, - onReconnect: () { - unawaited(ref.read(networkStatusProvider.notifier).check(optimistic: true)); + onReconnect: !ref.read(networkAdapterAvailableProvider) + ? null + : () { + unawaited(ref.read(networkStatusProvider.notifier).check(optimistic: true)); - final db = builtPowerSyncInstance; - final serverUrl = ref.read(wgerBaseProvider).serverUrl; - if (db == null || serverUrl == null) { - return; - } - // A manual reconnect is a deliberate new connection epoch. - final watchdog = ref.read(syncWatchdogProvider); - watchdog.reset(); - connectPowerSync( - db, - serverUrl, - ref.read(authenticatedHttpClientProvider), - watchdog, - ); - }, + final db = builtPowerSyncInstance; + final serverUrl = ref.read(wgerBaseProvider).serverUrl; + // The adapter re-check covers it disappearing while the + // dialog was open. + if (db == null || + serverUrl == null || + !ref.read(networkAdapterAvailableProvider)) { + return; + } + // A manual reconnect is a deliberate new connection epoch. + final watchdog = ref.read(syncWatchdogProvider); + watchdog.reset(); + connectPowerSync( + db, + serverUrl, + ref.read(authenticatedHttpClientProvider), + watchdog, + ); + }, ), ), ), diff --git a/lib/core/widgets/sync_status_dialog.dart b/lib/core/widgets/sync_status_dialog.dart index b1a9a1632..1b568c305 100644 --- a/lib/core/widgets/sync_status_dialog.dart +++ b/lib/core/widgets/sync_status_dialog.dart @@ -285,8 +285,8 @@ class SyncStatusDialog extends ConsumerWidget { ), // A stuck stream (firewall, VPN, flaky DNS) often recovers on a // fresh connection and can look healthy here while hanging, so the - // action is not gated on an error. Absent only while offline, where - // reconnecting would just spin against an unreachable backend. + // action is not gated on an error. Absent only without a network + // adapter, where there is no transport to reconnect over. if (onReconnect != null) TextButton( onPressed: () { diff --git a/lib/powersync/sync_watchdog.dart b/lib/powersync/sync_watchdog.dart index ad78c5ee9..a76964d29 100644 --- a/lib/powersync/sync_watchdog.dart +++ b/lib/powersync/sync_watchdog.dart @@ -163,6 +163,11 @@ class SyncStreamWatchdog { // A running timer deliberately survives: the probe misfires while a // large download saturates the line, and cancelling here would let // those misfires restart the detection over and over. + // A stall cleared here re-arms: its timer was consumed when it was + // flagged, and notStarted has no status event to restart it. + if (stalled.value && !_disarmed) { + _timer ??= Timer(timeout, _onTimeout); + } _stalledReason = null; stalled.value = false; } @@ -204,16 +209,9 @@ class SyncStreamWatchdog { stalled.value = true; final minutes = timeout.inMinutes; - if (_lastError case final error?) { - _logger.warning( - 'Sync has been failing for $minutes minutes without receiving any data.', - error, - ); - return; - } - // Naming the signature keeps the report honest: only the middle case is - // the blocked-middlebox one we used to assume for all of them. + // the blocked-middlebox one we used to assume for all of them. The last + // error seen (if any) rides along for the details. _logger.warning(switch (_stalledReason!) { StalledReason.notStarted => 'The sync client has not reported any state for $minutes minutes ' @@ -226,7 +224,7 @@ class SyncStreamWatchdog { 'Sync has been receiving data for $minutes minutes without completing ' 'a checkpoint, so none of it becomes visible. This is a client-side ' 'problem, not a blocked connection.', - }); + }, _lastError); } void _cancelTimer() { diff --git a/test/core/network/network_provider_test.dart b/test/core/network/network_provider_test.dart index c27c355e5..d93d45901 100644 --- a/test/core/network/network_provider_test.dart +++ b/test/core/network/network_provider_test.dart @@ -239,8 +239,9 @@ void main() { await container.read(networkStatusProvider.notifier).check(); final beforeEvent = probes; - // Adapter still reports a connection, but the backend has to prove itself. - connectivity.emit([ConnectivityResult.wifi]); + // An interface switch keeps the adapter up, but the backend has to prove + // itself on the new network. A same-content event is deliberately inert. + connectivity.emit([ConnectivityResult.mobile]); await pumpEventQueue(); expect(probes, greaterThan(beforeEvent)); @@ -252,10 +253,11 @@ void main() { await goOffline(container); expect(container.read(networkStatusProvider), isFalse); - // An adapter appears: optimistically online while the probe is pending. + // A connectivity change arrives: optimistically online while the probe + // for the new interface is pending. final probeCompleter = Completer(); reachabilityCheck = (_, _, _) => probeCompleter.future; - connectivity.emit([ConnectivityResult.wifi]); + connectivity.emit([ConnectivityResult.mobile]); await pumpEventQueue(); expect(container.read(networkStatusProvider), isTrue); @@ -518,6 +520,28 @@ void main() { expect(container.read(networkStatusProvider), isTrue, reason: 'one failure is not offline'); }); + test('an adapter loss during a pending probe is not coalesced away', () async { + // The change event must survive the pass in flight: that pass measured + // the old interface and its stale success must not stand. + reachabilityCheck = (_, _, _) async => (reachable: true, reason: 'test'); + final container = makeContainer(serverUrl: 'https://wger.example'); + final notifier = container.read(networkStatusProvider.notifier); + await pumpEventQueue(); + + final pendingProbe = Completer(); + reachabilityCheck = (_, _, _) => pendingProbe.future; + final inFlight = notifier.check(); + await pumpEventQueue(); + + connectivity.emit([ConnectivityResult.none]); + await pumpEventQueue(); + pendingProbe.complete((reachable: true, reason: 'stale wifi probe')); + await inFlight; + await pumpEventQueue(); + + expect(container.read(networkStatusProvider), isFalse); + }); + test('concurrent check calls join one probe pass and count one failure', () async { // A timer or connectivity-event pass can start while another pass is // mid-probe. Racing passes would each sample the same blip and count it diff --git a/test/core/widgets/app_bar_test.dart b/test/core/widgets/app_bar_test.dart index c41f0408a..7cc24c195 100644 --- a/test/core/widgets/app_bar_test.dart +++ b/test/core/widgets/app_bar_test.dart @@ -57,19 +57,25 @@ void main() { final i18n = AppLocalizationsEn(); late _FakeNetworkStatus networkStatus; + late SyncStreamWatchdog watchdog; setUp(() => networkStatus = _FakeNetworkStatus(false)); /// Renders the app bar with the current [networkStatus] fake, and opens the /// sync dialog through the [icon] the bar is expected to show. - Future pumpAppBar(WidgetTester tester, {IconData icon = Icons.cloud_off}) async { - final watchdog = SyncStreamWatchdog(); + Future pumpAppBar( + WidgetTester tester, { + IconData icon = Icons.cloud_off, + bool adapterAvailable = true, + }) async { + watchdog = SyncStreamWatchdog(); addTearDown(watchdog.dispose); await tester.pumpWidget( ProviderScope( overrides: [ networkStatusProvider.overrideWith(() => networkStatus), + networkAdapterAvailableProvider.overrideWithValue(adapterAvailable), wgerBaseProvider.overrideWithValue(WgerBaseProvider(serverUrl: 'https://wger.example')), syncStatus.overrideWithValue(buildSyncStatus()), syncWatchdogProvider.overrideWithValue(watchdog), @@ -117,4 +123,12 @@ void main() { expect(networkStatus.checks, [true]); }); + + testWidgets('hides the reconnect action while there is no adapter', (tester) async { + // The reachability status may be wrong, the adapter is a platform fact: + // without one there is no transport a reconnect could possibly use. + await pumpAppBar(tester, adapterAvailable: false); + + expect(find.text(i18n.syncStatusReconnect), findsNothing); + }); } diff --git a/test/powersync/sync_watchdog_test.dart b/test/powersync/sync_watchdog_test.dart index f361f7eb9..77bb46da0 100644 --- a/test/powersync/sync_watchdog_test.dart +++ b/test/powersync/sync_watchdog_test.dart @@ -175,12 +175,49 @@ void main() { } expect(watchdog.stalled.value, isTrue); - final warnings = logLines(Level.WARNING, 'has been failing'); + final warnings = logLines(Level.WARNING, 'may be blocked'); expect(warnings, hasLength(1)); expect(warnings.first.error.toString(), contains('boom')); }); }); + test('a retained error does not override the signature-specific warning', () { + fakeAsync((async) { + // Data arrived, then the timeout with an old error retained: the log + // must say "not applied", not falsely claim no data was received. + watchdog.onStatus(buildSyncStatus(connected: true, downloading: true)); + async.elapse(const Duration(seconds: 5)); + watchdog.onStatus(buildSyncStatus(downloadError: Exception('boom'))); + + async.elapse(watchdog.timeout + const Duration(seconds: 1)); + + expect(watchdog.stalledReason, StalledReason.notApplied); + final warnings = logLines(Level.WARNING, 'without completing'); + expect(warnings, hasLength(1)); + expect(warnings.first.error.toString(), contains('boom')); + }); + }); + + test('a stall cleared by an offline window is flagged again afterwards', () { + fakeAsync((async) { + watchdog.onConnectRequested(); + async.elapse(watchdog.timeout + const Duration(seconds: 1)); + expect(watchdog.stalled.value, isTrue); + + // The probe drops out briefly; clearing the flag must not end the + // detection, the notStarted case has no status event to restart it. + watchdog.offline = true; + expect(watchdog.stalled.value, isFalse); + async.elapse(watchdog.timeout); + + watchdog.offline = false; + async.elapse(watchdog.timeout + const Duration(seconds: 1)); + + expect(watchdog.stalled.value, isTrue); + expect(watchdog.stalledReason, StalledReason.notStarted); + }); + }); + test('an error while data is downloading does not flag anything', () { fakeAsync((async) { watchdog.onStatus(