Time out hanging token fetches instead of freezing the sync

This commit is contained in:
Roland Geider
2026-08-28 10:48:22 +02:00
parent dd43ee83a7
commit 9e9f2b1fbf
4 changed files with 86 additions and 6 deletions

View File

@@ -49,6 +49,11 @@ import 'package:wger/features/trophies/providers/trophy_notifier.dart';
part 'auth_notifier.g.dart';
/// Ceiling for the refresh POST. Callers are deduplicated onto one in-flight
/// refresh, so a request that never answers would block them all, PowerSync's
/// credential fetch included.
const tokenRefreshTimeout = Duration(seconds: 15);
@Riverpod(keepAlive: true)
class AuthNotifier extends _$AuthNotifier {
final _logger = Logger('AuthNotifier');
@@ -614,11 +619,13 @@ class AuthNotifier extends _$AuthNotifier {
final appVersion = current.applicationVersion ?? await PackageInfo.fromPlatform();
final http.Response response;
try {
response = await _api.postTokenRefresh(
refreshToken: refreshToken,
serverUrl: serverUrl,
appVersion: appVersion,
);
response = await _api
.postTokenRefresh(
refreshToken: refreshToken,
serverUrl: serverUrl,
appVersion: appVersion,
)
.timeout(tokenRefreshTimeout);
} on Exception catch (e, s) {
_logger.warning(
'refreshAccessToken: network error, keeping session so local data stays accessible',

View File

@@ -17,6 +17,7 @@
*/
// This file performs setup of the PowerSync database
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -103,6 +104,11 @@ class DjangoConnector extends PowerSyncBackendConnector {
/// Resets on app restart.
final Set<String> _reportedFailedOps = {};
/// Ceiling for one token fetch. On token expiry the SDK awaits the fetch
/// inline in its sync loop, so a request that never answers would freeze
/// sync, disconnect() included, until the process restarts.
static const credentialFetchTimeout = Duration(seconds: 30);
/// Spacing between repeated "backend unreachable" log lines while the
/// credential fetch keeps failing, so PowerSync's retry loop doesn't
/// flood the app logs during a longer outage.
@@ -140,7 +146,7 @@ class DjangoConnector extends PowerSyncBackendConnector {
// https://docs.powersync.com/usage/installation/authentication-setup/custom
final Map<String, dynamic> session;
try {
session = await apiClient.getPowersyncToken();
session = await apiClient.getPowersyncToken().timeout(credentialFetchTimeout);
} on http.ClientException catch (e) {
// Backend unreachable. Null would mean "not logged in" to the SDK and
// surface as a CredentialsException; rethrowing keeps it a connection
@@ -150,6 +156,9 @@ class DjangoConnector extends PowerSyncBackendConnector {
} on SocketException catch (e) {
_logUnreachable(e.message);
rethrow;
} on TimeoutException {
_logUnreachable('token fetch timed out after ${credentialFetchTimeout.inSeconds}s');
rethrow;
}
_logReachableAgain();

View File

@@ -21,6 +21,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' show AppLifecycleState;
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -967,6 +968,41 @@ void main() {
verifyNever(mockSecureStorage.writeRefreshToken(any));
});
test('a hanging refresh POST times out and keeps the session', () {
// Callers are deduplicated onto one in-flight refresh, so a POST that
// never answers would block them all, PowerSync's credential fetch
// included. The timeout must land in the keep-session branch.
fakeAsync((async) {
var seeded = false;
seedHeadlessBundle().then((_) => seeded = true);
async.flushMicrotasks();
expect(seeded, isTrue);
when(mockSecureStorage.readRefreshToken()).thenAnswer((_) async => 'old-refresh');
when(
mockClient.post(tRefresh, headers: anyNamed('headers'), body: anyNamed('body')),
).thenAnswer((_) => Completer<Response>().future);
final container = makeContainer();
AuthState? state;
container.read(authProvider.future).then((s) => state = s);
async.flushMicrotasks();
expect(state, isNotNull);
var completed = false;
container.read(authProvider.notifier).refreshAccessToken().then((_) => completed = true);
async.elapse(tokenRefreshTimeout - const Duration(seconds: 1));
expect(completed, isFalse);
async.elapse(const Duration(seconds: 2));
expect(completed, isTrue);
expect(container.read(authProvider).value!.isAuth, isTrue);
verifyNever(mockSecureStorage.writeRefreshToken(any));
});
});
test('clearSessionOnly keeps the DB-owner marker (the local DB is preserved)', () async {
// An involuntary clear keeps the local DB on disk, so its owner marker
// must survive too: it is what lets a *different* user signing in later

View File

@@ -21,6 +21,7 @@ import 'dart:convert';
import 'dart:io';
import 'package:drift/drift.dart' show GeneratedColumnWithTypeConverter;
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
@@ -384,6 +385,33 @@ void main() {
await expectLater(connector.fetchCredentials(), throwsA(isA<http.ClientException>()));
});
test('times out when the token request hangs', () {
// On token expiry the SDK awaits fetchCredentials inline in its sync
// loop; without the ceiling a request that never answers freezes sync
// (disconnect included) until process restart.
fakeAsync((async) {
final mockApi = MockApiClient();
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
when(
mockApi.getPowersyncToken(),
).thenAnswer((_) => Completer<Map<String, dynamic>>().future);
Object? error;
connector.fetchCredentials().then<void>(
(_) {},
onError: (Object e) {
error = e;
},
);
async.elapse(DjangoConnector.credentialFetchTimeout - const Duration(seconds: 1));
expect(error, isNull);
async.elapse(const Duration(seconds: 2));
expect(error, isA<TimeoutException>());
});
});
test('anchors expiresAt to the local clock via the token lifetime', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(