mirror of
https://github.com/wger-project/flutter.git
synced 2026-12-03 02:24:30 +01:00
Connect PowerSync on the adapter state, not on the reachability probe
This commit is contained in:
@@ -97,6 +97,42 @@ Future<ProbeResult> _defaultReachabilityCheck(
|
||||
@visibleForTesting
|
||||
Duration? networkProbeInterval = const Duration(seconds: 30);
|
||||
|
||||
/// Whether the device has a network adapter at all (wifi, mobile, ethernet...)
|
||||
///
|
||||
/// This is a platform fact and may therefore gate a connection attempt, unlike
|
||||
/// the reachability probe behind [NetworkStatus], which is only an indication.
|
||||
/// Starts out true so nothing waits for the first answer of the platform
|
||||
/// channel; an adapterless device corrects it a moment later.
|
||||
@Riverpod(keepAlive: true)
|
||||
class NetworkAdapterAvailable extends _$NetworkAdapterAvailable {
|
||||
final _logger = Logger('NetworkStatus');
|
||||
|
||||
@override
|
||||
bool build() {
|
||||
final sub = Connectivity().onConnectivityChanged.listen(_update);
|
||||
ref.onDispose(sub.cancel);
|
||||
unawaited(_seed());
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _seed() async {
|
||||
final conn = await Connectivity().checkConnectivity();
|
||||
if (ref.mounted) {
|
||||
_update(conn);
|
||||
}
|
||||
}
|
||||
|
||||
/// An empty list means no connection either, hence [Iterable.any] rather
|
||||
/// than a check for [ConnectivityResult.none].
|
||||
void _update(List<ConnectivityResult> conn) {
|
||||
final available = conn.any((c) => c != ConnectivityResult.none);
|
||||
if (available != state) {
|
||||
_logger.info('Network adapter ${available ? 'available' : 'gone'}');
|
||||
}
|
||||
state = available;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class NetworkStatus extends _$NetworkStatus {
|
||||
final _logger = Logger('NetworkStatus');
|
||||
|
||||
@@ -8,6 +8,77 @@ part of 'network_provider.dart';
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Whether the device has a network adapter at all (wifi, mobile, ethernet...)
|
||||
///
|
||||
/// This is a platform fact and may therefore gate a connection attempt, unlike
|
||||
/// the reachability probe behind [NetworkStatus], which is only an indication.
|
||||
/// Starts out true so nothing waits for the first answer of the platform
|
||||
/// channel; an adapterless device corrects it a moment later.
|
||||
|
||||
@ProviderFor(NetworkAdapterAvailable)
|
||||
final networkAdapterAvailableProvider = NetworkAdapterAvailableProvider._();
|
||||
|
||||
/// Whether the device has a network adapter at all (wifi, mobile, ethernet...)
|
||||
///
|
||||
/// This is a platform fact and may therefore gate a connection attempt, unlike
|
||||
/// the reachability probe behind [NetworkStatus], which is only an indication.
|
||||
/// Starts out true so nothing waits for the first answer of the platform
|
||||
/// channel; an adapterless device corrects it a moment later.
|
||||
final class NetworkAdapterAvailableProvider
|
||||
extends $NotifierProvider<NetworkAdapterAvailable, bool> {
|
||||
/// Whether the device has a network adapter at all (wifi, mobile, ethernet...)
|
||||
///
|
||||
/// This is a platform fact and may therefore gate a connection attempt, unlike
|
||||
/// the reachability probe behind [NetworkStatus], which is only an indication.
|
||||
/// Starts out true so nothing waits for the first answer of the platform
|
||||
/// channel; an adapterless device corrects it a moment later.
|
||||
NetworkAdapterAvailableProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'networkAdapterAvailableProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$networkAdapterAvailableHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
NetworkAdapterAvailable create() => NetworkAdapterAvailable();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(bool value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<bool>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$networkAdapterAvailableHash() => r'ba15e4720bf675523b1c5e697ba66e1a3c4e324e';
|
||||
|
||||
/// Whether the device has a network adapter at all (wifi, mobile, ethernet...)
|
||||
///
|
||||
/// This is a platform fact and may therefore gate a connection attempt, unlike
|
||||
/// the reachability probe behind [NetworkStatus], which is only an indication.
|
||||
/// Starts out true so nothing waits for the first answer of the platform
|
||||
/// channel; an adapterless device corrects it a moment later.
|
||||
|
||||
abstract class _$NetworkAdapterAvailable extends $Notifier<bool> {
|
||||
bool build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<bool, bool>;
|
||||
final element =
|
||||
ref.element as $ClassProviderElement<AnyNotifier<bool, bool>, bool, Object?, Object?>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(NetworkStatus)
|
||||
final networkStatusProvider = NetworkStatusProvider._();
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:wger/core/form_screen.dart';
|
||||
@@ -56,24 +58,23 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget {
|
||||
icon: Icon(status.icon),
|
||||
onPressed: () => showDialog<void>(
|
||||
context: context,
|
||||
// The dialog watches the sync state itself; only the server URL
|
||||
// and the offline gate are snapshots taken when it opens.
|
||||
// No reconnect while offline: the app deliberately disconnects
|
||||
// there (see powerSyncInstance). The tap-time check covers the
|
||||
// network dropping while the dialog is open
|
||||
// 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
|
||||
builder: (_) => SyncStatusDialog(
|
||||
serverUrl: ref.read(wgerBaseProvider).serverUrl,
|
||||
onReconnect: !ref.read(networkStatusProvider)
|
||||
? null
|
||||
: () {
|
||||
final db = builtPowerSyncInstance;
|
||||
final serverUrl = ref.read(wgerBaseProvider).serverUrl;
|
||||
if (db == null || serverUrl == null || !ref.read(networkStatusProvider)) {
|
||||
return;
|
||||
}
|
||||
ref.read(syncWatchdogProvider).reset();
|
||||
connectPowerSync(db, serverUrl, ref.read(authenticatedHttpClientProvider));
|
||||
},
|
||||
onReconnect: () {
|
||||
unawaited(ref.read(networkStatusProvider.notifier).check(optimistic: true));
|
||||
|
||||
final db = builtPowerSyncInstance;
|
||||
final serverUrl = ref.read(wgerBaseProvider).serverUrl;
|
||||
if (db == null || serverUrl == null) {
|
||||
return;
|
||||
}
|
||||
ref.read(syncWatchdogProvider).reset();
|
||||
connectPowerSync(db, serverUrl, ref.read(authenticatedHttpClientProvider));
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -100,28 +100,36 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
|
||||
}
|
||||
});
|
||||
|
||||
// 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) {
|
||||
// Gated on the network adapter only, never on the reachability probe: a
|
||||
// probe failure is an indication, an unreachable backend is PowerSync's own
|
||||
// retry loop to handle (the connector throttles its log output while the
|
||||
// backend does not answer). Reconnecting while already connected is safe and
|
||||
// doubles as the "retry now" signal when the adapter comes back.
|
||||
void syncConnection(bool hasAdapter) {
|
||||
if (hasAdapter) {
|
||||
final serverUrl = ref.read(wgerBaseProvider).serverUrl;
|
||||
if (serverUrl != null) {
|
||||
_logger.info('Device online, connecting to the sync service');
|
||||
_logger.info('Network adapter available, connecting to the sync service');
|
||||
connectPowerSync(db, serverUrl, client);
|
||||
} else {
|
||||
_logger.info('Device online, but no server configured: not connecting');
|
||||
_logger.info('Network adapter available, but no server configured: not connecting');
|
||||
}
|
||||
} else {
|
||||
_logger.info('Device offline, disconnecting from the sync service');
|
||||
_logger.info('No network adapter, disconnecting from the sync service');
|
||||
db.disconnect();
|
||||
// Deliberate disconnect: an offline device is not a blocked stream.
|
||||
watchdog.reset();
|
||||
}
|
||||
}
|
||||
|
||||
syncConnection(ref.read(networkStatusProvider));
|
||||
ref.listen(networkStatusProvider, (_, isOnline) => syncConnection(isOnline));
|
||||
syncConnection(ref.read(networkAdapterAvailableProvider));
|
||||
ref.listen(networkAdapterAvailableProvider, (_, hasAdapter) => syncConnection(hasAdapter));
|
||||
|
||||
// The probe stays a diagnostic input for the watchdog: while short REST
|
||||
// requests fail too, a stream without checkpoints says nothing about the
|
||||
// blocked middlebox the watchdog looks for.
|
||||
watchdog.offline = !ref.read(networkStatusProvider);
|
||||
ref.listen(networkStatusProvider, (_, isOnline) => watchdog.offline = !isOnline);
|
||||
|
||||
ref.onDispose(() {
|
||||
_builtInstance = null;
|
||||
|
||||
@@ -46,4 +46,4 @@ final class PowerSyncInstanceProvider
|
||||
}
|
||||
}
|
||||
|
||||
String _$powerSyncInstanceHash() => r'83bc0e7e421a0aa82c0ceb2d097367484c9dc87a';
|
||||
String _$powerSyncInstanceHash() => r'24189f75fce866ceb03e07a4c5236cdb94b64639';
|
||||
|
||||
@@ -55,6 +55,7 @@ class SyncStreamWatchdog {
|
||||
Timer? _timer;
|
||||
DateTime? _lastCheckpoint;
|
||||
bool _sawStatus = false;
|
||||
bool _offline = false;
|
||||
|
||||
/// Last error seen since the watchdog was armed, for the warning. Kept
|
||||
/// across status events: a retry loop clears the error while it reconnects
|
||||
@@ -101,14 +102,33 @@ class SyncStreamWatchdog {
|
||||
// already stalled there is nothing new to detect (and no reason to log
|
||||
// the warning again), so the timer stays off until recovery.
|
||||
if (!_disarmed &&
|
||||
!_offline &&
|
||||
!stalled.value &&
|
||||
(status.connecting || status.connected || _lastError != null)) {
|
||||
_timer ??= Timer(timeout, _onTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
/// Call when the app disconnects on purpose (offline gate, logout), so a
|
||||
/// device that is simply offline is never reported as blocked.
|
||||
/// Whether the backend is currently unreachable for plain REST requests as
|
||||
/// well. While set the watchdog stays quiet: a stream that delivers nothing
|
||||
/// against a backend that answers nothing is not the blocked-stream case.
|
||||
/// Unlike [reset] this keeps the connection epoch, so a brief false offline
|
||||
/// does not restart the detection from scratch.
|
||||
set offline(bool value) {
|
||||
if (value == _offline) {
|
||||
return;
|
||||
}
|
||||
_offline = value;
|
||||
if (value) {
|
||||
_cancelTimer();
|
||||
stalled.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Call when the app disconnects on purpose (adapter loss, logout, manual
|
||||
/// reconnect), so a device that is simply not connected is never reported as
|
||||
/// blocked. Starts a new connection epoch, see [offline] for the softer
|
||||
/// variant.
|
||||
void reset() {
|
||||
_cancelTimer();
|
||||
_disarmed = false;
|
||||
|
||||
@@ -302,6 +302,66 @@ void main() {
|
||||
expect(offline.first.message, contains('no network adapter'));
|
||||
});
|
||||
|
||||
group('networkAdapterAvailableProvider', () {
|
||||
test('starts available and stays there once the platform confirms an adapter', () async {
|
||||
final container = makeContainer();
|
||||
|
||||
// Nothing waits for the platform channel to answer.
|
||||
expect(container.read(networkAdapterAvailableProvider), isTrue);
|
||||
|
||||
await pumpEventQueue();
|
||||
expect(container.read(networkAdapterAvailableProvider), isTrue);
|
||||
});
|
||||
|
||||
test('turns false once the platform reports no adapter', () async {
|
||||
connectivity.current = [ConnectivityResult.none];
|
||||
final container = makeContainer();
|
||||
container.read(networkAdapterAvailableProvider);
|
||||
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(container.read(networkAdapterAvailableProvider), isFalse);
|
||||
});
|
||||
|
||||
test('an empty result list counts as no adapter', () async {
|
||||
connectivity.current = [];
|
||||
final container = makeContainer();
|
||||
container.read(networkAdapterAvailableProvider);
|
||||
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(container.read(networkAdapterAvailableProvider), isFalse);
|
||||
});
|
||||
|
||||
test('follows the adapter change events in both directions', () async {
|
||||
final container = makeContainer();
|
||||
container.read(networkAdapterAvailableProvider);
|
||||
await pumpEventQueue();
|
||||
|
||||
connectivity.emit([ConnectivityResult.none]);
|
||||
await pumpEventQueue();
|
||||
expect(container.read(networkAdapterAvailableProvider), isFalse);
|
||||
|
||||
connectivity.emit([ConnectivityResult.mobile]);
|
||||
await pumpEventQueue();
|
||||
expect(container.read(networkAdapterAvailableProvider), isTrue);
|
||||
});
|
||||
|
||||
test('a failed reachability probe leaves the adapter state alone', () async {
|
||||
// The whole point of the split: the probe may be wrong, the adapter is
|
||||
// a platform fact and gates the PowerSync connection.
|
||||
reachabilityCheck = (_, _, _) async => (reachable: false, reason: 'test');
|
||||
final container = makeContainer(serverUrl: 'https://wger.example');
|
||||
container.read(networkAdapterAvailableProvider);
|
||||
|
||||
await container.read(networkStatusProvider.notifier).check();
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(container.read(networkStatusProvider), isFalse);
|
||||
expect(container.read(networkAdapterAvailableProvider), isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
test('periodically re-probes on the configured interval', () async {
|
||||
networkProbeInterval = const Duration(milliseconds: 50);
|
||||
var probeCount = 0;
|
||||
|
||||
@@ -503,6 +503,39 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get allowSelfSignedCertsTitle =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#allowSelfSignedCertsTitle),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#allowSelfSignedCertsTitle),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get allowSelfSignedCertsDetail =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#allowSelfSignedCertsDetail),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#allowSelfSignedCertsDetail),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get certsNotVerifiedTitle =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#certsNotVerifiedTitle),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#certsNotVerifiedTitle),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get authOptionPasswordTitle =>
|
||||
(super.noSuchMethod(
|
||||
@@ -1662,6 +1695,14 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get meal =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#meal),
|
||||
returnValue: _i3.dummyValue<String>(this, Invocation.getter(#meal)),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get mealLogged =>
|
||||
(super.noSuchMethod(
|
||||
@@ -3628,6 +3669,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get settingsVerboseLogging =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#settingsVerboseLogging),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#settingsVerboseLogging),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get settingsVerboseLoggingDescription =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#settingsVerboseLoggingDescription),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#settingsVerboseLoggingDescription),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get aboutPageTitle =>
|
||||
(super.noSuchMethod(
|
||||
@@ -4250,6 +4313,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get useDynamicColor =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#useDynamicColor),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#useDynamicColor),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get youAreOffline =>
|
||||
(super.noSuchMethod(
|
||||
@@ -4492,6 +4566,39 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get syncStatusStalledHint =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#syncStatusStalledHint),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#syncStatusStalledHint),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get syncStatusReconnect =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#syncStatusReconnect),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#syncStatusReconnect),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get syncStatusNeverSynced =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#syncStatusNeverSynced),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#syncStatusNeverSynced),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get filterNutriscore =>
|
||||
(super.noSuchMethod(
|
||||
@@ -4602,6 +4709,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String certsNotVerifiedDetail(String? host) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#certsNotVerifiedDetail, [host]),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.method(#certsNotVerifiedDetail, [host]),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String exerciseNr(String? nr) =>
|
||||
(super.noSuchMethod(
|
||||
@@ -4954,6 +5072,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String syncStatusPendingUploads(int? count) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(#syncStatusPendingUploads, [count]),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.method(#syncStatusPendingUploads, [count]),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String filterNutriscoreOrBetter(String? grade) =>
|
||||
(super.noSuchMethod(
|
||||
|
||||
105
test/core/widgets/app_bar_test.dart
Normal file
105
test/core/widgets/app_bar_test.dart
Normal file
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:wger/core/network/base_provider.dart';
|
||||
import 'package:wger/core/network/network_provider.dart';
|
||||
import 'package:wger/core/network/wger_base.dart';
|
||||
import 'package:wger/core/widgets/app_bar.dart';
|
||||
import 'package:wger/database/powersync/powersync.dart'
|
||||
show pendingUploadCountProvider, syncStatus, syncWatchdogProvider;
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations_en.dart';
|
||||
import 'package:wger/powersync/sync_watchdog.dart';
|
||||
|
||||
import '../../helpers/sync_status.dart';
|
||||
|
||||
/// A [NetworkStatus] resolving to a fixed value, recording the re-probes the
|
||||
/// reconnect action asks for.
|
||||
class _FakeNetworkStatus extends NetworkStatus {
|
||||
_FakeNetworkStatus(this._online);
|
||||
|
||||
final bool _online;
|
||||
final checks = <bool>[];
|
||||
|
||||
@override
|
||||
bool build() => _online;
|
||||
|
||||
@override
|
||||
Future<bool> check({
|
||||
Duration timeout = const Duration(seconds: 1),
|
||||
bool optimistic = false,
|
||||
}) async {
|
||||
checks.add(optimistic);
|
||||
return _online;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
final i18n = AppLocalizationsEn();
|
||||
|
||||
late _FakeNetworkStatus networkStatus;
|
||||
|
||||
setUp(() => networkStatus = _FakeNetworkStatus(false));
|
||||
|
||||
Future<void> pumpAppBar(WidgetTester tester) async {
|
||||
final watchdog = SyncStreamWatchdog();
|
||||
addTearDown(watchdog.dispose);
|
||||
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
networkStatusProvider.overrideWith(() => networkStatus),
|
||||
wgerBaseProvider.overrideWithValue(WgerBaseProvider(serverUrl: 'https://wger.example')),
|
||||
syncStatus.overrideWithValue(buildSyncStatus()),
|
||||
syncWatchdogProvider.overrideWithValue(watchdog),
|
||||
pendingUploadCountProvider.overrideWith((ref) => const Stream<int>.empty()),
|
||||
],
|
||||
child: const MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: Locale('en'),
|
||||
home: Scaffold(appBar: MainAppBar('Test')),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byIcon(Icons.cloud_off));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('offers the reconnect action while the status says offline', (tester) async {
|
||||
// The status is exactly what the user is trying to override here, so
|
||||
// gating the button on it would lock them out.
|
||||
await pumpAppBar(tester);
|
||||
|
||||
expect(find.text(i18n.syncStatusReconnect), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('re-probes the network when reconnect is tapped', (tester) async {
|
||||
await pumpAppBar(tester);
|
||||
|
||||
await tester.tap(find.text(i18n.syncStatusReconnect));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(networkStatus.checks, [true]);
|
||||
});
|
||||
}
|
||||
@@ -1429,6 +1429,29 @@ class MockDriftPowersyncDatabase extends _i1.Mock implements _i4.DriftPowersyncD
|
||||
)
|
||||
as _i3.GenerationContext);
|
||||
|
||||
@override
|
||||
_i3.GenerationContext $writeUpdateInsertable(
|
||||
_i3.TableInfo<_i3.Table, dynamic>? table,
|
||||
_i3.Insertable<dynamic>? insertable, {
|
||||
int? startIndex,
|
||||
}) =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.method(
|
||||
#$writeUpdateInsertable,
|
||||
[table, insertable],
|
||||
{#startIndex: startIndex},
|
||||
),
|
||||
returnValue: _FakeGenerationContext_52(
|
||||
this,
|
||||
Invocation.method(
|
||||
#$writeUpdateInsertable,
|
||||
[table, insertable],
|
||||
{#startIndex: startIndex},
|
||||
),
|
||||
),
|
||||
)
|
||||
as _i3.GenerationContext);
|
||||
|
||||
@override
|
||||
String $expandVar(int? start, int? amount) =>
|
||||
(super.noSuchMethod(
|
||||
|
||||
@@ -179,6 +179,47 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
test('stays quiet while the backend is unreachable for plain requests', () {
|
||||
fakeAsync((async) {
|
||||
watchdog.offline = true;
|
||||
watchdog.onStatus(buildSyncStatus(connecting: true));
|
||||
|
||||
async.elapse(watchdog.timeout * 2);
|
||||
|
||||
expect(watchdog.stalled.value, isFalse);
|
||||
expect(records, isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
test('going offline cancels a pending timer and clears the flag', () {
|
||||
fakeAsync((async) {
|
||||
watchdog.onStatus(buildSyncStatus(connecting: true));
|
||||
async.elapse(watchdog.timeout);
|
||||
expect(watchdog.stalled.value, isTrue);
|
||||
|
||||
watchdog.offline = true;
|
||||
expect(watchdog.stalled.value, isFalse);
|
||||
|
||||
async.elapse(watchdog.timeout * 2);
|
||||
expect(watchdog.stalled.value, isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
test('re-arms on the next status once the backend answers again', () {
|
||||
fakeAsync((async) {
|
||||
watchdog.offline = true;
|
||||
watchdog.onStatus(buildSyncStatus(connecting: true));
|
||||
async.elapse(watchdog.timeout);
|
||||
expect(watchdog.stalled.value, isFalse);
|
||||
|
||||
watchdog.offline = false;
|
||||
watchdog.onStatus(buildSyncStatus(connecting: true));
|
||||
async.elapse(watchdog.timeout);
|
||||
|
||||
expect(watchdog.stalled.value, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
test('re-arms after reset() for the next connection epoch', () {
|
||||
fakeAsync((async) {
|
||||
watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));
|
||||
|
||||
Reference in New Issue
Block a user