diff --git a/lib/database/powersync/powersync.dart b/lib/database/powersync/powersync.dart index d7d42b3c5..4fcfafcd1 100644 --- a/lib/database/powersync/powersync.dart +++ b/lib/database/powersync/powersync.dart @@ -25,6 +25,7 @@ import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:stream_transform/stream_transform.dart'; import 'package:wger/powersync/connector.dart'; import 'package:wger/powersync/schema.dart'; +import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/wger_base.dart'; part 'powersync.g.dart'; @@ -39,8 +40,23 @@ Future powerSyncInstance(Ref ref) async { await db.initialize(); await _createRawTables(db); - final baseProvider = ref.read(wgerBaseProvider); - connectPowerSync(db, baseProvider.serverUrl!); + // Connect to the sync service only while the device is online. PowerSync's + // own retry loop would otherwise log a credential error on every iteration + // against an unreachable backend + void syncConnection(bool isOnline) { + if (isOnline) { + final serverUrl = ref.read(wgerBaseProvider).serverUrl; + if (serverUrl != null) { + connectPowerSync(db, serverUrl); + } + } else { + db.disconnect(); + } + } + + syncConnection(ref.read(networkStatusProvider)); + ref.listen(networkStatusProvider, (_, isOnline) => syncConnection(isOnline)); + ref.onDispose(db.close); return db; diff --git a/lib/powersync/connector.dart b/lib/powersync/connector.dart index b3a5913e1..c191296b5 100644 --- a/lib/powersync/connector.dart +++ b/lib/powersync/connector.dart @@ -18,6 +18,7 @@ // This file performs setup of the PowerSync database import 'dart:convert'; +import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; @@ -71,11 +72,23 @@ class DjangoConnector extends PowerSyncBackendConnector { /// Get a token to authenticate against the PowerSync instance. @override Future fetchCredentials() async { - // Somewhat contrived to illustrate usage, see auth docs here: + // See the auth docs here: // https://docs.powersync.com/usage/installation/authentication-setup/custom - final session = await apiClient.getPowersyncToken(); - final token = session['token'] as String; + final Map session; + try { + session = await apiClient.getPowersyncToken(); + } on http.ClientException catch (e) { + // Backend unreachable (offline). Returning null skips this attempt; + // PowerSync retries on its own schedule. Without this, the raw + // SocketException stack trace floods the logs on every retry. + logger.fine('PowerSync credential fetch skipped, backend unreachable: ${e.message}'); + return null; + } on SocketException catch (e) { + logger.fine('PowerSync credential fetch skipped, backend unreachable: ${e.message}'); + return null; + } + final token = session['token'] as String; final payload = decodeJwtPayload(token); return PowerSyncCredentials( endpoint: session['powersync_url'], @@ -185,10 +198,9 @@ class DjangoConnector extends PowerSyncBackendConnector { final record = { 'table': op.table, 'data': _genericTransform(op.table, op.opData, op.id), - // 'data': {'id': op.id, ...?op.opData}, }; - logger.finer('Uploading record $record to server with operation ${op.op}'); + // logger.finer('Uploading record $record to server with operation ${op.op}'); final http.Response response; switch (op.op) { @@ -206,6 +218,14 @@ class DjangoConnector extends PowerSyncBackendConnector { _handleUploadResponse(op, response); } await transaction.complete(); + } on http.ClientException catch (e) { + // Backend unreachable (offline or down). The transaction stays queued; + // rethrowing lets PowerSync retry it once the backend is reachable. + logger.fine('Upload deferred, backend unreachable: ${e.message}'); + rethrow; + } on SocketException catch (e) { + logger.fine('Upload deferred, backend unreachable: ${e.message}'); + rethrow; } on Exception catch (e) { logger.severe('Error uploading data', e); // Error may be retryable - e.g. network error or temporary server error. diff --git a/lib/providers/network_provider.dart b/lib/providers/network_provider.dart index 7805399f3..ebe800a87 100644 --- a/lib/providers/network_provider.dart +++ b/lib/providers/network_provider.dart @@ -32,17 +32,22 @@ part 'network_provider.g.dart'; /// Returns whether the wger backend is actually reachable. /// /// Given [probeUri] any HTTP response counts as reachable, only a -/// network-level error or timeout counts as offline. When [probeUri] is null -/// (no server configured yet, e.g. on the login screen) it falls back to a -/// DNS lookup so there is still a sane online/offline signal. +/// network-level error or timeout counts as offline. The request carries +/// [userAgent] so the probe is identifiable in server logs. When [probeUri] is +/// null (no server configured yet, e.g. on the login screen) it falls back to +/// a DNS lookup so there is still a sane online/offline signal. /// /// Tests can swap this for a deterministic stub via `installFakeConnectivity()` /// so the test runner doesn't make real network calls. @visibleForTesting -Future Function(Uri? probeUri, Duration timeout) reachabilityCheck = +Future Function(Uri? probeUri, String? userAgent, Duration timeout) reachabilityCheck = _defaultReachabilityCheck; -Future _defaultReachabilityCheck(Uri? probeUri, Duration timeout) async { +Future _defaultReachabilityCheck( + Uri? probeUri, + String? userAgent, + Duration timeout, +) async { // No server configured yet: fall back to a generic internet check. if (probeUri == null) { try { @@ -57,7 +62,12 @@ Future _defaultReachabilityCheck(Uri? probeUri, Duration timeout) async { try { // Any response (even 401/403) proves the server answered. HEAD keeps it // cheap and the version endpoint does not hit the database. - await client.head(probeUri).timeout(timeout); + await client + .head( + probeUri, + headers: userAgent != null ? {HttpHeaders.userAgentHeader: userAgent} : null, + ) + .timeout(timeout); return true; } catch (e) { if (isNetworkError(e)) { @@ -69,11 +79,18 @@ Future _defaultReachabilityCheck(Uri? probeUri, Duration timeout) async { } } +/// Interval for the active backend re-probe (see [NetworkStatus]). Tests set +/// this to `null` to disable the periodic timer; a pending timer would +/// otherwise fail the test runner. +@visibleForTesting +Duration? networkProbeInterval = const Duration(seconds: 30); + @Riverpod(keepAlive: true) class NetworkStatus extends _$NetworkStatus { final _logger = Logger('NetworkStatus'); StreamSubscription>? _sub; + Timer? _probeTimer; @override bool build() { @@ -99,8 +116,17 @@ class NetworkStatus extends _$NetworkStatus { } }); + // Connectivity events only fire on adapter changes, so an active re-probe + // is needed to notice a backend that goes down (or comes back) while the + // network stays up. + final probeInterval = networkProbeInterval; + if (probeInterval != null) { + _probeTimer = Timer.periodic(probeInterval, (_) => check()); + } + ref.onDispose(() { _sub?.cancel(); + _probeTimer?.cancel(); }); } @@ -122,8 +148,9 @@ class NetworkStatus extends _$NetworkStatus { if (conn.every((c) => c == ConnectivityResult.none)) { return false; } + final base = ref.read(wgerBaseProvider); final probeUri = base.serverUrl != null ? base.makeUrl('version') : null; - return reachabilityCheck(probeUri, timeout); + return reachabilityCheck(probeUri, base.getAppNameHeaderValue(), timeout); } } diff --git a/test/fake_connectivity.dart b/test/fake_connectivity.dart index b93a1bfbe..6ac3fb34e 100644 --- a/test/fake_connectivity.dart +++ b/test/fake_connectivity.dart @@ -37,7 +37,7 @@ import 'package:wger/providers/network_provider.dart'; /// for the entire file). void installFakeConnectivity() { ConnectivityPlatform.instance = _FakeConnectivityPlatform(); - reachabilityCheck = (_, _) async => true; + reachabilityCheck = (_, _, _) async => true; } class _FakeConnectivityPlatform extends ConnectivityPlatform with MockPlatformInterfaceMixin { diff --git a/test/flutter_test_config.dart b/test/flutter_test_config.dart new file mode 100644 index 000000000..1462d3f06 --- /dev/null +++ b/test/flutter_test_config.dart @@ -0,0 +1,31 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:async'; + +import 'package:wger/providers/network_provider.dart'; + +/// Global setup wrapped around every test file under `test/`. +/// +/// Disables [NetworkStatus]'s periodic backend re-probe: a `Timer.periodic` +/// left running past a test fails the test runner with a pending-timer error. +/// Production keeps the default interval. +Future testExecutable(FutureOr Function() testMain) async { + networkProbeInterval = null; + await testMain(); +} diff --git a/test/powersync/connector_test.dart b/test/powersync/connector_test.dart index 73c2ae4ba..a4deb6087 100644 --- a/test/powersync/connector_test.dart +++ b/test/powersync/connector_test.dart @@ -19,6 +19,7 @@ import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:wger/powersync/api_client.dart'; @@ -255,5 +256,15 @@ void main() { expect(creds.userId, isNull); expect(creds.expiresAt, isNull); }); + + test('returns null when the backend is unreachable', () async { + final mockApi = MockApiClient(); + final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi); + when( + mockApi.getPowersyncToken(), + ).thenThrow(http.ClientException('Connection refused')); + + expect(await connector.fetchCredentials(), isNull); + }); }); } diff --git a/test/providers/network_provider_test.dart b/test/providers/network_provider_test.dart new file mode 100644 index 000000000..4bea152dd --- /dev/null +++ b/test/providers/network_provider_test.dart @@ -0,0 +1,237 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:async'; + +import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/network_provider.dart'; +import 'package:wger/providers/wger_base.dart'; + +/// Connectivity fake that each test can drive: [current] sets what +/// `checkConnectivity()` reports, [emit] pushes a change event. +class _FakeConnectivity extends ConnectivityPlatform with MockPlatformInterfaceMixin { + List current = [ConnectivityResult.wifi]; + final _controller = StreamController>.broadcast(); + + @override + Future> checkConnectivity() async => current; + + @override + Stream> get onConnectivityChanged => _controller.stream; + + void emit(List results) { + current = results; + _controller.add(results); + } + + void dispose() => _controller.close(); +} + +/// Drives the server URL exposed through [wgerBaseProvider] in the +/// server-URL-change test. +class _ServerUrl extends Notifier { + @override + String? build() => null; + + void set(String? value) => state = value; +} + +final _serverUrlProvider = NotifierProvider<_ServerUrl, String?>(_ServerUrl.new); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _FakeConnectivity connectivity; + late Future Function(Uri?, String?, Duration) originalReachability; + late Duration? originalProbeInterval; + + setUp(() { + originalReachability = reachabilityCheck; + originalProbeInterval = networkProbeInterval; + connectivity = _FakeConnectivity(); + ConnectivityPlatform.instance = connectivity; + }); + + tearDown(() { + reachabilityCheck = originalReachability; + networkProbeInterval = originalProbeInterval; + connectivity.dispose(); + }); + + ProviderContainer makeContainer({String? serverUrl}) { + return ProviderContainer.test( + overrides: [ + wgerBaseProvider.overrideWithValue(WgerBaseProvider(serverUrl: serverUrl)), + ], + ); + } + + test('starts optimistically online before the first probe completes', () async { + reachabilityCheck = (_, _, _) async => false; + final container = makeContainer(serverUrl: 'https://wger.example'); + + expect(container.read(networkStatusProvider), isTrue); + + // Drain the build-time probe so it doesn't outlive the test. + await pumpEventQueue(); + }); + + test('reports offline without probing when there is no network adapter', () async { + connectivity.current = [ConnectivityResult.none]; + var probed = false; + reachabilityCheck = (_, _, _) async { + probed = true; + return true; + }; + final container = makeContainer(serverUrl: 'https://wger.example'); + + final result = await container.read(networkStatusProvider.notifier).check(); + + expect(result, isFalse); + expect(container.read(networkStatusProvider), isFalse); + expect(probed, isFalse); + }); + + test('reports online when the backend probe succeeds', () async { + reachabilityCheck = (_, _, _) async => true; + final container = makeContainer(serverUrl: 'https://wger.example'); + + await container.read(networkStatusProvider.notifier).check(); + + expect(container.read(networkStatusProvider), isTrue); + }); + + test('reports offline when the backend probe fails', () async { + reachabilityCheck = (_, _, _) async => false; + final container = makeContainer(serverUrl: 'https://wger.example'); + + await container.read(networkStatusProvider.notifier).check(); + + expect(container.read(networkStatusProvider), isFalse); + }); + + test('probes the server version endpoint when a server URL is configured', () async { + Uri? probedUri; + reachabilityCheck = (uri, _, _) async { + probedUri = uri; + return true; + }; + final base = WgerBaseProvider(serverUrl: 'https://wger.example'); + final container = ProviderContainer.test( + overrides: [wgerBaseProvider.overrideWithValue(base)], + ); + + await container.read(networkStatusProvider.notifier).check(); + + expect(probedUri, base.makeUrl('version')); + }); + + test('probes without a URL (generic fallback) when no server is configured', () async { + Uri? probedUri; + var probed = false; + reachabilityCheck = (uri, _, _) async { + probedUri = uri; + probed = true; + return true; + }; + final container = makeContainer(); + + await container.read(networkStatusProvider.notifier).check(); + + expect(probed, isTrue); + expect(probedUri, isNull); + }); + + test('passes the app User-Agent to the probe', () async { + String? probedUserAgent; + reachabilityCheck = (_, userAgent, _) async { + probedUserAgent = userAgent; + return true; + }; + final base = WgerBaseProvider(serverUrl: 'https://wger.example'); + final container = ProviderContainer.test( + overrides: [wgerBaseProvider.overrideWithValue(base)], + ); + + await container.read(networkStatusProvider.notifier).check(); + + expect(probedUserAgent, base.getAppNameHeaderValue()); + }); + + test('re-probes when a connectivity change event arrives', () async { + reachabilityCheck = (_, _, _) async => true; + final container = makeContainer(serverUrl: 'https://wger.example'); + await container.read(networkStatusProvider.notifier).check(); + expect(container.read(networkStatusProvider), isTrue); + + // Adapter still reports a connection, but the backend probe now fails. + reachabilityCheck = (_, _, _) async => false; + connectivity.emit([ConnectivityResult.wifi]); + await pumpEventQueue(); + + expect(container.read(networkStatusProvider), isFalse); + }); + + test('re-probes when the configured server URL changes (login)', () async { + final probedUris = []; + reachabilityCheck = (uri, _, _) async { + probedUris.add(uri); + return true; + }; + final container = ProviderContainer.test( + overrides: [ + wgerBaseProvider.overrideWith( + (ref) => WgerBaseProvider(serverUrl: ref.watch(_serverUrlProvider)), + ), + ], + ); + await container.read(networkStatusProvider.notifier).check(); + final beforeLogin = probedUris.length; + + container.read(_serverUrlProvider.notifier).set('https://wger.example'); + // Force the dependent wgerBaseProvider to rebuild so NetworkStatus's + // ref.listen fires. + container.read(wgerBaseProvider); + await pumpEventQueue(); + + expect(probedUris.length, greaterThan(beforeLogin)); + expect(probedUris.last, isNotNull); + }); + + test('periodically re-probes on the configured interval', () async { + networkProbeInterval = const Duration(milliseconds: 50); + var probeCount = 0; + reachabilityCheck = (_, _, _) async { + probeCount++; + return true; + }; + final container = makeContainer(serverUrl: 'https://wger.example'); + container.read(networkStatusProvider); + await pumpEventQueue(); + final afterInit = probeCount; + + await Future.delayed(const Duration(milliseconds: 160)); + await pumpEventQueue(); + + expect(probeCount, greaterThan(afterInit)); + }); +}