Detect a sync stream that is blocked on the network path

This might help debugging when an ad-blocker, vpn or similar interferes with
the connections to the sync service

See #1271
This commit is contained in:
Roland Geider
2026-07-23 14:56:29 +02:00
parent ed623f9108
commit b277e81088
12 changed files with 359 additions and 4 deletions

View File

@@ -24,7 +24,7 @@ import 'package:wger/core/network/network_provider.dart';
import 'package:wger/core/settings_dashboard_widgets_screen.dart';
import 'package:wger/core/widgets/about.dart';
import 'package:wger/core/widgets/sync_status_dialog.dart';
import 'package:wger/database/powersync/powersync.dart' show syncStatus;
import 'package:wger/database/powersync/powersync.dart' show syncStatus, syncWatchdogProvider;
import 'package:wger/features/account/providers/account_notifier.dart';
import 'package:wger/features/account/widgets/forms.dart';
import 'package:wger/features/account/widgets/settings.dart';
@@ -53,7 +53,11 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget {
icon: Icon(status.icon),
onPressed: () => showDialog<void>(
context: context,
builder: (_) => SyncStatusDialog(syncState),
// Like syncState, the stalled flag is a snapshot taken when the dialog opens
builder: (_) => SyncStatusDialog(
syncState,
stalled: ref.read(syncWatchdogProvider).stalled.value,
),
),
),
IconButton(

View File

@@ -20,6 +20,7 @@ import 'package:flutter/material.dart';
import 'package:powersync/powersync.dart'
show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus;
import 'package:wger/core/formatting/formatting.dart';
import 'package:wger/core/widgets/log_overview.dart' show LogOverviewPage;
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/powersync/connector.dart' show RetryableUploadException;
@@ -94,7 +95,12 @@ String? _categoriseSyncError(Object error) {
class SyncStatusDialog extends StatelessWidget {
final SyncStatus _status;
const SyncStatusDialog(this._status, {super.key});
/// True when the sync stream keeps reconnecting without ever receiving
/// data (see SyncStreamWatchdog). There is no error to show in that
/// case, so the dialog adds a hint about likely network-side blockers.
final bool stalled;
const SyncStatusDialog(this._status, {this.stalled = false, super.key});
@override
Widget build(BuildContext context) {
@@ -133,6 +139,15 @@ class SyncStatusDialog extends StatelessWidget {
),
],
),
if (stalled && _status.anyError == null) ...[
const SizedBox(height: 8),
Text(
i18n.syncStatusStalledHint,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
const SizedBox(height: 16),
// Last sync timestamp if available
@@ -172,6 +187,17 @@ class SyncStatusDialog extends StatelessWidget {
],
),
actions: [
// The stalled hint and the WARNING land in the application logs;
// give the user a direct path to them.
if (stalled && _status.anyError == null)
TextButton(
onPressed: () {
final navigator = Navigator.of(context);
navigator.pop();
navigator.pushNamed(LogOverviewPage.routeName);
},
child: Text(i18n.applicationLogs),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(MaterialLocalizations.of(context).closeButtonLabel),

View File

@@ -33,6 +33,7 @@ import 'package:wger/core/network/wger_base.dart';
import 'package:wger/powersync/api_client.dart';
import 'package:wger/powersync/connector.dart';
import 'package:wger/powersync/schema.dart';
import 'package:wger/powersync/sync_watchdog.dart';
part 'powersync.g.dart';
@@ -50,6 +51,16 @@ PowerSyncDatabase? _builtInstance;
/// those paths need.
PowerSyncDatabase? get builtPowerSyncInstance => _builtInstance;
/// Watches the sync status for a stream that keeps reconnecting without ever
/// delivering data (e.g. blocked by a VPN or firewall) and flags it, see
/// [SyncStreamWatchdog]. Fed from the DB's status stream by
/// [powerSyncInstanceProvider].
final syncWatchdogProvider = Provider<SyncStreamWatchdog>((ref) {
final watchdog = SyncStreamWatchdog();
ref.onDispose(watchdog.dispose);
return watchdog;
});
@Riverpod(keepAlive: true)
Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
final db = PowerSyncDatabase(
@@ -62,6 +73,8 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
_builtInstance = db;
final client = ref.read(authenticatedHttpClientProvider);
final watchdog = ref.read(syncWatchdogProvider);
final statusSubscription = db.statusStream.listen(watchdog.onStatus);
// 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
@@ -74,6 +87,8 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
}
} else {
db.disconnect();
// Deliberate disconnect: an offline device is not a blocked stream.
watchdog.reset();
}
}
@@ -82,6 +97,8 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
ref.onDispose(() {
_builtInstance = null;
statusSubscription.cancel();
watchdog.reset();
db.close();
});

View File

@@ -1148,6 +1148,7 @@
"syncStatusDialogTitle": "Synchronisierungsstatus",
"syncStatusLastSynced": "Letzte Synchronisierung",
"syncStatusErrorDetails": "Fehlerdetails",
"syncStatusStalledHint": "Die Verbindung zum Synchronisierungsdienst scheint blockiert zu werden. Möglicherweise stört ein VPN, Werbeblocker, Virenscanner oder eine Firewall in diesem Netzwerk.",
"sessionExpired": "Deine Sitzung ist abgelaufen, bitte melde dich erneut an",
"endBeforeStart": "Der Endwert darf nicht vor dem Startwert liegen",
"minLengthRoutine": "Die Routine muss mindestens {number} Wochen lang sein",

View File

@@ -1396,6 +1396,10 @@
"@syncStatusErrorDetails": {
"description": "Header of the expandable section in the sync status dialog that reveals the raw error message"
},
"syncStatusStalledHint": "The connection to the sync service seems to be blocked. A VPN, ad blocker, antivirus or firewall on this network may be interfering.",
"@syncStatusStalledHint": {
"description": "Hint shown in the sync status dialog when the app keeps connecting but never receives any sync data, which usually means something on the network is blocking the connection"
},
"filterNutriscore": "Nutri-Score filter",
"@filterNutriscore": {
"description": "Heading for the Nutri-Score slider in the ingredient search filter dialog"

View File

@@ -1185,6 +1185,7 @@
"syncStatusDialogTitle": "Estado de sincronización",
"syncStatusLastSynced": "Última sincronización",
"syncStatusErrorDetails": "Detalles del error",
"syncStatusStalledHint": "La conexión con el servicio de sincronización parece estar bloqueada. Es posible que una VPN, un bloqueador de anuncios, un antivirus o un cortafuegos de esta red estén interfiriendo.",
"sessionExpired": "Tu sesión ha expirado, inicia sesión de nuevo",
"weightOrRepsRequired": "Introduce un peso, repeticiones o ambos",
"timeStartEndBothOrNeither": "Indica la hora de inicio y de fin, o deja ambas vacías",

View File

@@ -1156,6 +1156,7 @@
"syncStatusDialogTitle": "État de la synchronisation",
"syncStatusLastSynced": "Dernière synchronisation",
"syncStatusErrorDetails": "Détails de l'erreur",
"syncStatusStalledHint": "La connexion au service de synchronisation semble être bloquée. Un VPN, un bloqueur de publicités, un antivirus ou un pare-feu sur ce réseau interfère peut-être.",
"sessionExpired": "Votre session a expiré, veuillez vous reconnecter",
"weightOrRepsRequired": "Veuillez saisir un poids, des répétitions, ou les deux",
"timeStartEndBothOrNeither": "Indiquez l'heure de début et de fin, ou laissez les deux vides",

View File

@@ -0,0 +1,124 @@
/*
* 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 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:powersync/powersync.dart' show SyncStatus;
final _logger = Logger('powersync');
/// Flags a sync stream that keeps reconnecting without ever delivering a
/// checkpoint.
///
/// That is the signature of a middlebox (VPN, ad blocker, antivirus, carrier
/// proxy) silently swallowing the long-lived stream request while short REST
/// requests still pass: the SDK sees a clean end-of-stream on every
/// iteration, so no exception is thrown, nothing is logged above FINE and
/// `SyncStatus.anyError` stays null. The UI shows "Connecting" forever
/// without a trace.
///
/// The watchdog arms a timer while the client wants to sync but has not
/// received a checkpoint in this connection epoch. Checkpoint progress
/// disarms it until [reset]; an active download or a surfaced error pauses
/// it (those cases are visible through other channels). If the timer
/// survives [timeout], [stalled] flips to true (the sync status dialog
/// shows a hint) and a WARNING lands in the app logs.
class SyncStreamWatchdog {
SyncStreamWatchdog({this.timeout = const Duration(minutes: 2)});
final Duration timeout;
/// True while the stream looks blocked. Consumed by the sync status dialog.
final ValueNotifier<bool> stalled = ValueNotifier(false);
Timer? _timer;
DateTime? _lastCheckpoint;
bool _sawStatus = false;
/// Set once a checkpoint arrived; the watchdog then stays quiet so a later
/// idle connection (status events stop while nothing changes) cannot
/// re-trigger it. [reset] re-arms for the next connection epoch.
bool _disarmed = false;
void onStatus(SyncStatus status) {
final checkpoint = status.lastSyncedAt;
// Progress is a NEW checkpoint: the first status event replays the
// timestamp persisted in the local DB (which may be weeks old on a
// blocked device), so only a change to a non-null value counts.
final madeProgress = _sawStatus && checkpoint != null && checkpoint != _lastCheckpoint;
_sawStatus = true;
_lastCheckpoint = checkpoint;
if (madeProgress) {
_disarmed = true;
_cancelTimer();
if (stalled.value) {
_logger.info('Sync stream recovered, checkpoint received');
stalled.value = false;
}
return;
}
// Downloading means data is flowing (a first checkpoint on a large
// account can take a while); an error is already surfaced by the sync
// status dialog. Neither is the silent failure we are watching for.
if (status.downloading || status.anyError != null) {
_cancelTimer();
return;
}
// A `connecting` flag briefly dropping between two retry iterations must
// NOT clear the timer: the silent connect/EOF loop would reset it on
// every cycle. Only [reset] (deliberate disconnect) clears it. While
// 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 && !stalled.value && (status.connecting || status.connected)) {
_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.
void reset() {
_cancelTimer();
_disarmed = false;
stalled.value = false;
}
void dispose() {
_cancelTimer();
stalled.dispose();
}
void _onTimeout() {
_timer = null;
stalled.value = true;
_logger.warning(
'Sync stream keeps terminating without receiving any data. The '
'connection to the sync service may be blocked by a VPN, ad blocker, '
'antivirus or firewall on this network.',
);
}
void _cancelTimer() {
_timer?.cancel();
_timer = null;
}
}

View File

@@ -410,7 +410,7 @@ packages:
source: hosted
version: "5.0.1"
fake_async:
dependency: transitive
dependency: "direct dev"
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"

View File

@@ -81,6 +81,7 @@ dev_dependencies:
sdk: flutter
build_runner: ^2.15.0
cider: ^0.2.10
fake_async: ^1.3.1
# Used to stub the connectivity_plus platform interface
connectivity_plus_platform_interface: ^2.1.0
# Used to stub the url_launcher platform interface for the web-handoff test

View File

@@ -143,6 +143,38 @@ void main() {
expect(find.text(i18n.syncStatusErrorDetails), findsNothing);
});
testWidgets('shows the blocked-connection hint when stalled without an error', (tester) async {
await tester.pumpWidget(
_wrap(const SyncStatusDialog(SyncStatus(connecting: true), stalled: true)),
);
await tester.pumpAndSettle();
expect(find.text(i18n.syncStatusStalledHint), findsOneWidget);
expect(find.text(i18n.applicationLogs), findsOneWidget);
});
testWidgets('omits the stalled hint when not stalled', (tester) async {
await _pumpDialog(tester, const SyncStatus(connecting: true));
expect(find.text(i18n.syncStatusStalledHint), findsNothing);
expect(find.text(i18n.applicationLogs), findsNothing);
});
testWidgets('prefers the real error over the stalled hint', (tester) async {
await tester.pumpWidget(
_wrap(
SyncStatusDialog(
SyncStatus(connecting: true, downloadError: Exception('boom')),
stalled: true,
),
),
);
await tester.pumpAndSettle();
expect(find.text(i18n.syncStatusStalledHint), findsNothing);
expect(find.text(i18n.syncStatusError), findsOneWidget);
});
testWidgets('renders the expander with the raw error message when present', (tester) async {
await _pumpDialog(
tester,

View File

@@ -0,0 +1,144 @@
/*
* 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/>.
*/
// SyncStatus constructor is marked as @internal
// ignore_for_file: invalid_use_of_internal_member
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:logging/logging.dart';
import 'package:powersync/powersync.dart' show SyncStatus;
import 'package:wger/powersync/sync_watchdog.dart';
void main() {
late SyncStreamWatchdog watchdog;
late List<LogRecord> records;
setUp(() {
watchdog = SyncStreamWatchdog();
records = [];
final sub = Logger.root.onRecord.listen(records.add);
addTearDown(sub.cancel);
addTearDown(watchdog.dispose);
});
Iterable<LogRecord> logLines(Level level, String needle) =>
records.where((r) => r.level == level && r.message.contains(needle));
test('flags a connection that never delivers a checkpoint', () {
fakeAsync((async) {
watchdog.onStatus(const SyncStatus(connecting: true));
async.elapse(watchdog.timeout - const Duration(seconds: 1));
expect(watchdog.stalled.value, isFalse);
async.elapse(const Duration(seconds: 2));
expect(watchdog.stalled.value, isTrue);
expect(logLines(Level.WARNING, 'may be blocked'), hasLength(1));
});
});
test('the silent connect/EOF retry loop does not reset the timer', () {
fakeAsync((async) {
// Mimic the status flapping of an iteration that starts, ends cleanly
// and retries: connecting toggles, lastSyncedAt never moves.
for (var i = 0; i < 20; i++) {
watchdog.onStatus(const SyncStatus(connecting: true));
async.elapse(const Duration(seconds: 5));
watchdog.onStatus(const SyncStatus());
async.elapse(const Duration(seconds: 5));
}
expect(watchdog.stalled.value, isTrue);
expect(logLines(Level.WARNING, 'may be blocked'), hasLength(1));
});
});
test('a checkpoint disarms the watchdog, idle time does not re-trigger it', () {
fakeAsync((async) {
watchdog.onStatus(const SyncStatus(connecting: true));
async.elapse(const Duration(seconds: 10));
watchdog.onStatus(SyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));
// A healthy connection can sit idle without new status events for far
// longer than the timeout.
async.elapse(watchdog.timeout * 3);
expect(watchdog.stalled.value, isFalse);
expect(records, isEmpty);
});
});
test('an active download holds the watchdog off', () {
fakeAsync((async) {
watchdog.onStatus(const SyncStatus(connected: true, downloading: true));
async.elapse(watchdog.timeout * 2);
expect(watchdog.stalled.value, isFalse);
});
});
test('a surfaced sync error holds the watchdog off', () {
fakeAsync((async) {
watchdog.onStatus(SyncStatus(connecting: true, downloadError: Exception('boom')));
async.elapse(watchdog.timeout * 2);
expect(watchdog.stalled.value, isFalse);
});
});
test('recovers and logs once when a checkpoint finally arrives', () {
fakeAsync((async) {
watchdog.onStatus(const SyncStatus(connecting: true));
async.elapse(watchdog.timeout);
expect(watchdog.stalled.value, isTrue);
watchdog.onStatus(SyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));
expect(watchdog.stalled.value, isFalse);
expect(logLines(Level.INFO, 'recovered'), hasLength(1));
});
});
test('reset() clears the pending timer and the stalled flag', () {
fakeAsync((async) {
watchdog.onStatus(const SyncStatus(connecting: true));
async.elapse(watchdog.timeout);
expect(watchdog.stalled.value, isTrue);
watchdog.reset();
expect(watchdog.stalled.value, isFalse);
// No further timer fires after the reset.
async.elapse(watchdog.timeout * 2);
expect(watchdog.stalled.value, isFalse);
});
});
test('re-arms after reset() for the next connection epoch', () {
fakeAsync((async) {
watchdog.onStatus(SyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));
watchdog.reset();
watchdog.onStatus(const SyncStatus(connecting: true));
async.elapse(watchdog.timeout);
expect(watchdog.stalled.value, isTrue);
});
});
}