Report reachability from the bottom of the client stack

This commit is contained in:
Roland Geider
2026-08-21 16:04:52 +02:00
parent a9f2c07914
commit 2a596349df
5 changed files with 107 additions and 146 deletions

View File

@@ -22,10 +22,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
import 'package:wger/core/error_dialogs.dart';
import 'package:wger/core/errors.dart';
import 'package:wger/core/network/auth_notifier.dart';
import 'package:wger/core/network/auth_state.dart';
import 'package:wger/core/network/network_provider.dart';
/// Pre-emptive refresh leeway: if the access JWT will expire within this
/// window we refresh before sending the request. Chosen to absorb mild
@@ -56,7 +54,6 @@ class AuthHttpClient extends http.BaseClient {
final AuthState? Function() _readAuth;
final Future<void> Function() _refresh;
final Future<void> Function() _onSessionExpired;
final void Function({required bool reachable}) _reportReachability;
final _logger = Logger('AuthHttpClient');
AuthHttpClient({
@@ -64,12 +61,10 @@ class AuthHttpClient extends http.BaseClient {
required AuthState? Function() readAuth,
required Future<void> Function() refresh,
required Future<void> Function() onSessionExpired,
required void Function({required bool reachable}) reportReachability,
}) : _inner = inner,
_readAuth = readAuth,
_refresh = refresh,
_onSessionExpired = onSessionExpired,
_reportReachability = reportReachability;
_onSessionExpired = onSessionExpired;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
@@ -82,7 +77,7 @@ class AuthHttpClient extends http.BaseClient {
}
_applyAuthHeader(request, credential);
final response = await _send(request);
final response = await _inner.send(request);
final canRetry =
response.statusCode == 401 && credential is JwtCredential && request is http.Request;
@@ -99,7 +94,7 @@ class AuthHttpClient extends http.BaseClient {
}
final retry = _cloneRequest(request, fresh);
final retryResponse = await _send(retry);
final retryResponse = await _inner.send(retry);
if (retryResponse.statusCode == 401) {
_logger.warning(
'Retry after refresh still returned 401 for '
@@ -115,23 +110,6 @@ class AuthHttpClient extends http.BaseClient {
@override
void close() => _inner.close();
/// Sends through the inner client and reports whether the backend answered
/// at all. Any response counts, including 4xx and 5xx: the server was
/// reached. Only a network-level failure says otherwise, and errors that
/// are not about the network say nothing either way.
Future<http.StreamedResponse> _send(http.BaseRequest request) async {
try {
final response = await _inner.send(request);
_reportReachability(reachable: true);
return response;
} catch (e) {
if (isNetworkError(e)) {
_reportReachability(reachable: false);
}
rethrow;
}
}
void _applyAuthHeader(http.BaseRequest req, AuthCredential? credential) {
if (credential == null) {
return;
@@ -171,12 +149,5 @@ final authenticatedHttpClientProvider = Provider<http.Client>(
await ref.read(authProvider.notifier).clearSessionOnly();
showSessionExpiredSnackbar();
},
// Read at call time, not captured: the auth flow invalidates
// networkStatusProvider after a login and a captured notifier would go
// stale. Only the write path, no dependency on the network status.
reportReachability: ({required bool reachable}) {
final status = ref.read(networkStatusProvider.notifier);
reachable ? status.reportRequestSuccess() : status.reportRequestFailure();
},
),
);

View File

@@ -69,7 +69,12 @@ const ISSUE_REFRESH_TOKEN_PATH = 'issue-refresh-token';
const HEADLESS_SESSION_TOKEN_HEADER = 'X-Session-Token';
/// HTTP client used by the auth notifier. Override in tests.
final authHttpClientProvider = Provider<http.Client>((ref) => http.Client());
final authHttpClientProvider = Provider<http.Client>(
(ref) => ReachabilityReportingClient(
http.Client(),
() => ref.read(networkStatusProvider.notifier),
),
);
@Riverpod(keepAlive: true)
class AuthNotifier extends _$AuthNotifier {

View File

@@ -323,3 +323,33 @@ class NetworkStatus extends _$NetworkStatus {
state = isOnline;
}
}
/// Feeds every request outcome into [NetworkStatus]: any response means the
/// backend was reached (4xx/5xx included), a network error means it was not.
/// Wrapped around the raw client, so auth traffic counts as a probe too.
class ReachabilityReportingClient extends http.BaseClient {
ReachabilityReportingClient(this._inner, this._status);
final http.Client _inner;
/// Resolved at call time: the auth flow invalidates [NetworkStatus] on
/// login and a captured notifier would go stale.
final NetworkStatus Function() _status;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
try {
final response = await _inner.send(request);
_status().reportRequestSuccess();
return response;
} catch (e) {
if (isNetworkError(e)) {
_status().reportRequestFailure();
}
rethrow;
}
}
@override
void close() => _inner.close();
}

View File

@@ -26,9 +26,8 @@ import 'package:mockito/mockito.dart';
import 'package:wger/core/network/auth_http_client.dart';
import 'package:wger/core/network/auth_notifier.dart';
import 'package:wger/core/network/auth_state.dart';
import 'package:wger/core/network/network_provider.dart';
import 'package:wger/core/network/network_provider.dart' show ReachabilityReportingClient;
import '../../helpers/fake_connectivity.dart';
import 'auth_http_client_test.mocks.dart';
/// Records the calls the provider's closures are supposed to route to the
@@ -62,20 +61,6 @@ class _RecordingAuthNotifier extends AuthNotifier {
}
}
/// Records what the provider's reachability closure routes to the notifier.
class _RecordingNetworkStatus extends NetworkStatus {
final reports = <bool>[];
@override
bool build() => true;
@override
void reportRequestSuccess() => reports.add(true);
@override
void reportRequestFailure() => reports.add(false);
}
@GenerateMocks([http.Client])
void main() {
// The provider's onSessionExpired shows a snackbar through
@@ -83,15 +68,10 @@ void main() {
// (no widget tree), so the snackbar is skipped instead of throwing.
TestWidgetsFlutterBinding.ensureInitialized();
// The provider reports every request outcome to NetworkStatus, which would
// otherwise reach for the real connectivity plugin and a DNS lookup.
installFakeConnectivity();
late MockClient inner;
late AuthState? auth;
late int refreshCalls;
late int sessionExpiredCalls;
late List<bool> reachabilityReports;
Future<void> Function() onRefresh = () async {};
AuthHttpClient buildClient() => AuthHttpClient(
@@ -105,7 +85,6 @@ void main() {
sessionExpiredCalls++;
auth = const AuthState();
},
reportReachability: ({required bool reachable}) => reachabilityReports.add(reachable),
);
/// Stubs a single response and returns the headers captured from the
@@ -131,7 +110,6 @@ void main() {
auth = null;
refreshCalls = 0;
sessionExpiredCalls = 0;
reachabilityReports = [];
onRefresh = () async {};
});
@@ -407,73 +385,19 @@ void main() {
});
});
group('reachability reporting', () {
// Every real request is a free, perfectly targeted probe for
// NetworkStatus, which is what keeps its cached status fresh.
Future<void> send() => buildClient().send(
http.Request('GET', Uri.parse('https://wger.example/api/v2/routine/')),
);
test('any response counts as reachable, including 4xx and 5xx', () async {
for (final status in [200, 403, 500]) {
reachabilityReports = [];
when(inner.send(any)).thenAnswer(
(_) async => http.StreamedResponse(Stream.value(<int>[]), status),
);
await send();
expect(reachabilityReports, [true], reason: 'HTTP $status was not reported as reachable');
}
});
test('a network error reports unreachable', () async {
when(inner.send(any)).thenThrow(const SocketException('no route to host'));
await expectLater(send(), throwsA(isA<SocketException>()));
expect(reachabilityReports, [false]);
});
test('a non-network error reports nothing either way', () async {
when(inner.send(any)).thenThrow(const FormatException('broken response'));
await expectLater(send(), throwsA(isA<FormatException>()));
expect(reachabilityReports, isEmpty);
});
test('the retry after a refresh reports as well', () async {
auth = AuthState(
credential: JwtCredential(
accessToken: 'stale',
expiresAt: DateTime.now().toUtc().add(const Duration(hours: 1)),
),
);
onRefresh = () async => auth = AuthState(
credential: JwtCredential(
accessToken: 'fresh',
expiresAt: DateTime.now().toUtc().add(const Duration(hours: 1)),
),
);
var call = 0;
when(inner.send(any)).thenAnswer(
(_) async => http.StreamedResponse(Stream.value(<int>[]), ++call == 1 ? 401 : 200),
);
await send();
expect(reachabilityReports, [true, true]);
});
});
group('authenticatedHttpClientProvider', () {
// The tests above build the client with hand-written closures. These cover
// the wiring the app actually runs: the closures the provider hands to
// AuthHttpClient have to reach the notifier, or every request goes out
// unauthenticated and an expired session is never noticed.
late _RecordingAuthNotifier notifier;
late _RecordingNetworkStatus networkStatus;
test('the raw client is wrapped for reachability reporting', () {
// Wrapping sits at the bottom of the stack, so login and refresh
// traffic through the raw client feeds the network status as well.
final container = ProviderContainer.test();
expect(container.read(authHttpClientProvider), isA<ReachabilityReportingClient>());
});
JwtCredential jwt(String token) => JwtCredential(
accessToken: token,
@@ -482,12 +406,10 @@ void main() {
http.Client buildFromProvider(AuthState initial) {
notifier = _RecordingAuthNotifier(initial);
networkStatus = _RecordingNetworkStatus();
final container = ProviderContainer.test(
overrides: [
authHttpClientProvider.overrideWithValue(inner),
authProvider.overrideWith(() => notifier),
networkStatusProvider.overrideWith(() => networkStatus),
],
);
// The provider reads authProvider synchronously, so the state has to be
@@ -531,33 +453,6 @@ void main() {
);
});
test('reports a reached backend to the network status', () async {
// The closure resolves the notifier at call time; a captured one would
// go stale when the auth flow invalidates networkStatusProvider.
final client = buildFromProvider(AuthState(credential: jwt('token')));
await pumpEventQueue();
when(inner.send(any)).thenAnswer(
(_) async => http.StreamedResponse(Stream.value(<int>[]), 200),
);
await client.send(http.Request('GET', Uri.parse('https://wger.example/api/v2/routine/')));
expect(networkStatus.reports, [true]);
});
test('reports an unreachable backend to the network status', () async {
final client = buildFromProvider(AuthState(credential: jwt('token')));
await pumpEventQueue();
when(inner.send(any)).thenThrow(const SocketException('no route to host'));
await expectLater(
client.send(http.Request('GET', Uri.parse('https://wger.example/api/v2/routine/'))),
throwsA(isA<SocketException>()),
);
expect(networkStatus.reports, [false]);
});
test('a 401 that survives the refresh clears the session', () async {
final client = buildFromProvider(AuthState(credential: jwt('stale')));
await pumpEventQueue();

View File

@@ -17,12 +17,15 @@
*/
import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:logging/logging.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:wger/core/network/base_provider.dart';
@@ -49,6 +52,20 @@ class _FakeConnectivity extends ConnectivityPlatform with MockPlatformInterfaceM
void dispose() => _controller.close();
}
/// Records what [ReachabilityReportingClient] routes into the notifier.
class _RecordingNetworkStatus extends NetworkStatus {
final reports = <bool>[];
@override
bool build() => true;
@override
void reportRequestSuccess() => reports.add(true);
@override
void reportRequestFailure() => reports.add(false);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@@ -604,4 +621,47 @@ void main() {
expect(probeCount, greaterThan(afterInit));
});
group('ReachabilityReportingClient', () {
late _RecordingNetworkStatus status;
ReachabilityReportingClient buildClient(MockClient inner) {
status = _RecordingNetworkStatus();
final container = ProviderContainer.test(
overrides: [networkStatusProvider.overrideWith(() => status)],
);
return ReachabilityReportingClient(
inner,
() => container.read(networkStatusProvider.notifier),
);
}
Future<http.Response> get(http.Client client) =>
client.get(Uri.parse('https://wger.example/api/v2/routine/'));
test('any response reports the backend as reached, 4xx and 5xx included', () async {
for (final code in [200, 403, 500]) {
final client = buildClient(MockClient((_) async => http.Response('', code)));
await get(client);
expect(status.reports, [true], reason: 'HTTP $code was not reported');
}
});
test('a network error reports a failure and rethrows', () async {
final client = buildClient(MockClient((_) => throw const SocketException('no route')));
await expectLater(get(client), throwsA(isA<SocketException>()));
expect(status.reports, [false]);
});
test('an error that is not about the network reports nothing', () async {
final client = buildClient(MockClient((_) => throw const FormatException('broken')));
await expectLater(get(client), throwsA(isA<FormatException>()));
expect(status.reports, isEmpty);
});
});
}