mirror of
https://github.com/wger-project/flutter.git
synced 2026-11-29 01:18:35 +01:00
Merge pull request #1288 from wger-project/feature/better-handling-of-powersync-url
More intelligent powersync service URL handling
This commit is contained in:
@@ -20,6 +20,8 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_riverpod/misc.dart' show ProviderListenable;
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
/// Awaits the first value of `provider` by explicitly subscribing via
|
||||
/// [Ref.listen]. Use this in notifier methods (outside of `build()`)
|
||||
@@ -102,6 +104,64 @@ Uri makeHeadlessUri(String serverUrl, String path) {
|
||||
);
|
||||
}
|
||||
|
||||
final _probeLogger = Logger('powersync-probe');
|
||||
|
||||
/// Builds `<serverUrl>/ps/`, the default path under which wger's reverse
|
||||
/// proxy exposes the PowerSync service.
|
||||
String _defaultPowerSyncUrl(String serverUrl) {
|
||||
final server = Uri.parse(serverUrl);
|
||||
final basePath = server.path.endsWith('/')
|
||||
? server.path.substring(0, server.path.length - 1)
|
||||
: server.path;
|
||||
return Uri(
|
||||
scheme: server.scheme,
|
||||
host: server.host,
|
||||
port: server.port,
|
||||
path: '$basePath/ps/',
|
||||
).toString();
|
||||
}
|
||||
|
||||
/// Returns the first PowerSync endpoint that answers its liveness probe with
|
||||
/// a 200, or null when none does.
|
||||
///
|
||||
/// The `powersync_url` [provided] by the server's token endpoint is tried
|
||||
/// first, then `<serverUrl>/ps/` as a fallback. Probing instead of trusting
|
||||
/// [provided] rescues servers whose `SITE_URL` doesn't match the URL the app
|
||||
/// reaches them under (e.g. left at its `http://localhost` default): that
|
||||
/// value is unreachable from the device, while the reverse proxy usually
|
||||
/// still exposes the service under the default path.
|
||||
Future<String?> findLivePowerSyncUrl({
|
||||
required http.Client client,
|
||||
required String serverUrl,
|
||||
required String? provided,
|
||||
Duration probeTimeout = const Duration(seconds: 5),
|
||||
}) async {
|
||||
final parsed = provided == null ? null : Uri.tryParse(provided);
|
||||
final candidates = {
|
||||
if (parsed != null && parsed.hasScheme && parsed.host.isNotEmpty) provided!,
|
||||
_defaultPowerSyncUrl(serverUrl),
|
||||
};
|
||||
|
||||
for (final candidate in candidates) {
|
||||
final probeUri = Uri.parse(
|
||||
'$candidate${candidate.endsWith('/') ? '' : '/'}probes/liveness',
|
||||
);
|
||||
|
||||
// Log failed probes
|
||||
try {
|
||||
final response = await client.get(probeUri).timeout(probeTimeout);
|
||||
if (response.statusCode == 200) {
|
||||
return candidate;
|
||||
}
|
||||
_probeLogger.info('PowerSync probe: $probeUri returned ${response.statusCode}');
|
||||
} on Exception catch (e) {
|
||||
// Unreachable or timed out: try the next candidate.
|
||||
_probeLogger.info('PowerSync probe: $probeUri failed: $e');
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Builds the absolute URL for a server-side media file given its
|
||||
/// [relativePath] (the raw value of a Django `ImageField` / `FileField`
|
||||
/// as stored in the DB, e.g. `ingredients/42/foo.jpg`).
|
||||
|
||||
@@ -164,22 +164,27 @@ class ServerGating {
|
||||
return false;
|
||||
}
|
||||
final body = json.decode(tokenResponse.body) as Map<String, dynamic>;
|
||||
final powerSyncUrl = body['powersync_url'] as String?;
|
||||
if (powerSyncUrl == null || powerSyncUrl.isEmpty) {
|
||||
_logger.warning('PowerSync probe: empty powersync_url in token response');
|
||||
final providedUrl = body['powersync_url'] as String?;
|
||||
final powerSyncUrl = await findLivePowerSyncUrl(
|
||||
client: _client,
|
||||
serverUrl: serverUrl,
|
||||
provided: providedUrl,
|
||||
);
|
||||
if (powerSyncUrl == null) {
|
||||
_logger.warning(
|
||||
'PowerSync probe: no endpoint answered the liveness probe '
|
||||
'(server-provided powersync_url: "$providedUrl")',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
final probeUri = Uri.parse(
|
||||
'$powerSyncUrl${powerSyncUrl.endsWith('/') ? '' : '/'}probes/liveness',
|
||||
);
|
||||
final probeResponse = await _client.get(probeUri);
|
||||
if (probeResponse.statusCode == 200) {
|
||||
await _storage.markEverSynced();
|
||||
return true;
|
||||
if (powerSyncUrl != providedUrl) {
|
||||
_logger.warning(
|
||||
'PowerSync probe: server-provided powersync_url "$providedUrl" is '
|
||||
'unreachable, using $powerSyncUrl instead',
|
||||
);
|
||||
}
|
||||
_logger.warning('PowerSync probe: liveness returned ${probeResponse.statusCode}');
|
||||
return false;
|
||||
await _storage.markEverSynced();
|
||||
return true;
|
||||
} on Exception catch (e, s) {
|
||||
_logger.warning('PowerSync probe failed: $e', e, s);
|
||||
return false;
|
||||
|
||||
@@ -187,6 +187,7 @@ void connectPowerSync(PowerSyncDatabase db, String baseUrl, http.Client client)
|
||||
connector: DjangoConnector(
|
||||
baseUrl: baseUrl,
|
||||
apiClient: ApiClient(baseUrl, client: client),
|
||||
client: client,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import 'package:logging/logging.dart';
|
||||
import 'package:powersync/powersync.dart';
|
||||
import 'package:wger/core/error_dialogs.dart';
|
||||
import 'package:wger/core/exceptions/http_exception.dart';
|
||||
import 'package:wger/core/helpers.dart';
|
||||
import 'package:wger/core/network/jwt.dart';
|
||||
import 'package:wger/powersync/api_client.dart';
|
||||
|
||||
@@ -67,6 +68,9 @@ class DjangoConnector extends PowerSyncBackendConnector {
|
||||
final String baseUrl;
|
||||
final ApiClient apiClient;
|
||||
|
||||
/// Client for the endpoint liveness probes in [fetchCredentials].
|
||||
final http.Client _probeClient;
|
||||
|
||||
/// IDs of CRUD operations that already triggered a user-facing
|
||||
/// rejection dialog this session. Without this gate the same
|
||||
/// permanent-failure op would re-pop the dialog on every sync tick
|
||||
@@ -85,7 +89,26 @@ class DjangoConnector extends PowerSyncBackendConnector {
|
||||
/// reachable.
|
||||
DateTime? _lastUnreachableLogAt;
|
||||
|
||||
DjangoConnector({required this.baseUrl, required this.apiClient});
|
||||
/// Endpoint last announced in the logs. [fetchCredentials] runs on every
|
||||
/// token refresh, so the endpoint is only logged when it changes.
|
||||
String? _lastLoggedEndpoint;
|
||||
|
||||
/// When "no live PowerSync endpoint" was last logged; null while an
|
||||
/// endpoint resolves. Throttled like [_logUnreachable], since PowerSync
|
||||
/// re-drives [fetchCredentials] on its retry schedule.
|
||||
DateTime? _lastNoEndpointLogAt;
|
||||
|
||||
/// The `powersync_url` from the last token response and the endpoint it
|
||||
/// resolved to. While the server keeps advertising the same URL, the cached
|
||||
/// resolution is reused instead of re-probing on every token refresh (a dead
|
||||
/// advertised URL would otherwise cost a probe timeout each time). A failed
|
||||
/// resolution is never cached, so retries keep probing. Cleared on app
|
||||
/// restart with the connector.
|
||||
String? _lastProvidedUrl;
|
||||
String? _lastResolvedEndpoint;
|
||||
|
||||
DjangoConnector({required this.baseUrl, required this.apiClient, http.Client? client})
|
||||
: _probeClient = client ?? http.Client();
|
||||
|
||||
/// Get a token to authenticate against the PowerSync instance.
|
||||
@override
|
||||
@@ -109,8 +132,35 @@ class DjangoConnector extends PowerSyncBackendConnector {
|
||||
|
||||
final token = session['token'] as String;
|
||||
final payload = decodeJwtPayload(token);
|
||||
final provided = session['powersync_url'] as String?;
|
||||
String? endpoint;
|
||||
if (provided == _lastProvidedUrl && _lastResolvedEndpoint != null) {
|
||||
endpoint = _lastResolvedEndpoint;
|
||||
} else {
|
||||
endpoint = await findLivePowerSyncUrl(
|
||||
client: _probeClient,
|
||||
serverUrl: baseUrl,
|
||||
provided: provided,
|
||||
);
|
||||
if (endpoint != null) {
|
||||
_lastProvidedUrl = provided;
|
||||
_lastResolvedEndpoint = endpoint;
|
||||
}
|
||||
}
|
||||
if (endpoint == null) {
|
||||
// The wger backend answered (the token fetch above succeeded), so this
|
||||
// is a bad or down sync service, not the device being offline.
|
||||
// Returning null skips the attempt; PowerSync retries on its own.
|
||||
_logNoEndpoint();
|
||||
return null;
|
||||
}
|
||||
_lastNoEndpointLogAt = null;
|
||||
if (endpoint != _lastLoggedEndpoint) {
|
||||
logger.info('Connecting to PowerSync endpoint $endpoint');
|
||||
_lastLoggedEndpoint = endpoint;
|
||||
}
|
||||
return PowerSyncCredentials(
|
||||
endpoint: session['powersync_url'],
|
||||
endpoint: endpoint,
|
||||
token: token,
|
||||
userId: payload?['sub']?.toString(),
|
||||
expiresAt: jwtExpOnLocalClock(payload),
|
||||
@@ -128,6 +178,17 @@ class DjangoConnector extends PowerSyncBackendConnector {
|
||||
}
|
||||
}
|
||||
|
||||
/// Logs an unresolved PowerSync endpoint at WARNING, throttled to once per
|
||||
/// [unreachableLogInterval] per outage.
|
||||
void _logNoEndpoint() {
|
||||
final now = DateTime.now();
|
||||
final last = _lastNoEndpointLogAt;
|
||||
if (last == null || now.difference(last) >= unreachableLogInterval) {
|
||||
logger.warning('No PowerSync endpoint answered its liveness probe, skipping credentials');
|
||||
_lastNoEndpointLogAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes an outage announced by [_logUnreachable], if any.
|
||||
void _logReachableAgain() {
|
||||
if (_lastUnreachableLogAt != null) {
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
*/
|
||||
|
||||
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:wger/core/helpers.dart';
|
||||
|
||||
void main() {
|
||||
@@ -177,4 +180,154 @@ void main() {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
group('findLivePowerSyncUrl', () {
|
||||
const serverUrl = 'https://wger.example.com';
|
||||
|
||||
/// Client answering 200 only for the liveness probe of [liveEndpoint]
|
||||
/// (with or without its trailing slash); records every requested URL.
|
||||
MockClient liveOnlyAt(String liveEndpoint, [List<String>? requested]) {
|
||||
final probe = '$liveEndpoint${liveEndpoint.endsWith('/') ? '' : '/'}probes/liveness';
|
||||
return MockClient((request) async {
|
||||
requested?.add(request.url.toString());
|
||||
return request.url.toString() == probe
|
||||
? http.Response('{"ready":true}', 200)
|
||||
: http.Response('not found', 404);
|
||||
});
|
||||
}
|
||||
|
||||
test('uses the server-provided URL when it answers the probe', () async {
|
||||
final requested = <String>[];
|
||||
final client = liveOnlyAt('https://ps.example.com', requested);
|
||||
|
||||
expect(
|
||||
await findLivePowerSyncUrl(
|
||||
client: client,
|
||||
serverUrl: serverUrl,
|
||||
provided: 'https://ps.example.com',
|
||||
),
|
||||
'https://ps.example.com',
|
||||
);
|
||||
expect(requested, ['https://ps.example.com/probes/liveness']);
|
||||
});
|
||||
|
||||
test('falls back to <serverUrl>/ps/ when the provided URL does not answer', () async {
|
||||
// The #2432 shape: SITE_URL left at its localhost default, so the
|
||||
// advertised URL points at the device itself.
|
||||
expect(
|
||||
await findLivePowerSyncUrl(
|
||||
client: liveOnlyAt('$serverUrl/ps/'),
|
||||
serverUrl: serverUrl,
|
||||
provided: 'http://localhost/ps/',
|
||||
),
|
||||
'$serverUrl/ps/',
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back when probing the provided URL throws', () async {
|
||||
final client = MockClient((request) async {
|
||||
if (request.url.host == 'ps.example.com') {
|
||||
throw http.ClientException('Connection refused');
|
||||
}
|
||||
return http.Response('{"ready":true}', 200);
|
||||
});
|
||||
|
||||
expect(
|
||||
await findLivePowerSyncUrl(
|
||||
client: client,
|
||||
serverUrl: serverUrl,
|
||||
provided: 'https://ps.example.com',
|
||||
),
|
||||
'$serverUrl/ps/',
|
||||
);
|
||||
});
|
||||
|
||||
test('probes only the fallback for a missing URL', () async {
|
||||
final requested = <String>[];
|
||||
final client = liveOnlyAt('$serverUrl/ps/', requested);
|
||||
|
||||
expect(
|
||||
await findLivePowerSyncUrl(client: client, serverUrl: serverUrl, provided: null),
|
||||
'$serverUrl/ps/',
|
||||
);
|
||||
expect(requested, ['$serverUrl/ps/probes/liveness']);
|
||||
});
|
||||
|
||||
test('skips a URL without a scheme', () async {
|
||||
final requested = <String>[];
|
||||
final client = liveOnlyAt('$serverUrl/ps/', requested);
|
||||
|
||||
expect(
|
||||
await findLivePowerSyncUrl(
|
||||
client: client,
|
||||
serverUrl: serverUrl,
|
||||
provided: 'wger.example.com/ps/',
|
||||
),
|
||||
'$serverUrl/ps/',
|
||||
);
|
||||
expect(requested, ['$serverUrl/ps/probes/liveness']);
|
||||
});
|
||||
|
||||
test('returns null when no candidate answers', () async {
|
||||
expect(
|
||||
await findLivePowerSyncUrl(
|
||||
client: MockClient((_) async => http.Response('not found', 404)),
|
||||
serverUrl: serverUrl,
|
||||
provided: 'https://ps.example.com',
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test('logs failed probes at INFO with status code or exception', () async {
|
||||
final records = <LogRecord>[];
|
||||
final sub = Logger.root.onRecord.listen(records.add);
|
||||
addTearDown(sub.cancel);
|
||||
|
||||
final client = MockClient((request) async {
|
||||
if (request.url.host == 'ps.example.com') {
|
||||
throw http.ClientException('Connection refused');
|
||||
}
|
||||
return http.Response('bad gateway', 502);
|
||||
});
|
||||
await findLivePowerSyncUrl(
|
||||
client: client,
|
||||
serverUrl: serverUrl,
|
||||
provided: 'https://ps.example.com',
|
||||
);
|
||||
|
||||
final messages = records.where((r) => r.level == Level.INFO).map((r) => r.message);
|
||||
expect(
|
||||
messages,
|
||||
contains('PowerSync probe: https://ps.example.com/probes/liveness failed: '
|
||||
'ClientException: Connection refused'),
|
||||
);
|
||||
expect(
|
||||
messages,
|
||||
contains('PowerSync probe: $serverUrl/ps/probes/liveness returned 502'),
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps a sub-directory installation path in the fallback', () async {
|
||||
expect(
|
||||
await findLivePowerSyncUrl(
|
||||
client: liveOnlyAt('https://example.com/wger/ps/'),
|
||||
serverUrl: 'https://example.com/wger',
|
||||
provided: null,
|
||||
),
|
||||
'https://example.com/wger/ps/',
|
||||
);
|
||||
});
|
||||
|
||||
test('handles a trailing slash on the server URL', () async {
|
||||
expect(
|
||||
await findLivePowerSyncUrl(
|
||||
client: liveOnlyAt('$serverUrl/ps/'),
|
||||
serverUrl: '$serverUrl/',
|
||||
provided: null,
|
||||
),
|
||||
'$serverUrl/ps/',
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,6 +78,7 @@ void main() {
|
||||
final tMinAppVersion = Uri.parse('$serverUrl/api/v2/min-app-version/');
|
||||
final tPowerSyncToken = Uri.parse('$serverUrl/api/v2/powersync-token');
|
||||
final tLiveness = Uri.parse('${powerSyncUrl}probes/liveness');
|
||||
final tFallbackLiveness = Uri.parse('$serverUrl/ps/probes/liveness');
|
||||
final tIssueRefresh = Uri.parse('$serverUrl/api/v2/issue-refresh-token');
|
||||
final tHeadlessRefresh = Uri.parse('$serverUrl/allauth/app/v1/tokens/refresh');
|
||||
|
||||
@@ -157,6 +158,10 @@ void main() {
|
||||
);
|
||||
|
||||
when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('OK', 200));
|
||||
// When the advertised URL fails its probe, the resolution falls back to
|
||||
// <serverUrl>/ps/. A 404 keeps the "unreachable" scenarios unreachable;
|
||||
// fallback-specific tests override this.
|
||||
when(mockClient.get(tFallbackLiveness)).thenAnswer((_) async => Response('not found', 404));
|
||||
|
||||
// Default: the legacy-DRF → JWT migration POST silently fails as
|
||||
// "offline" so existing tests that seed PREFS_USER fall through to the
|
||||
@@ -447,11 +452,24 @@ void main() {
|
||||
final state = await container.read(authProvider.future);
|
||||
|
||||
expect(state.status, AuthStatus.powerSyncUnreachable);
|
||||
// Probe should never run if we can't resolve the URL.
|
||||
// The unusable advertised URL is never probed; only the
|
||||
// <serverUrl>/ps/ fallback is (dead here via the setUp default).
|
||||
verifyNever(mockClient.get(tLiveness));
|
||||
verify(mockClient.get(tFallbackLiveness)).called(1);
|
||||
},
|
||||
);
|
||||
|
||||
test('dead advertised URL but live <serverUrl>/ps/ fallback → loggedIn', () async {
|
||||
when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('Bad Gateway', 502));
|
||||
when(mockClient.get(tFallbackLiveness)).thenAnswer((_) async => Response('OK', 200));
|
||||
|
||||
final container = makeContainer();
|
||||
final state = await container.read(authProvider.future);
|
||||
|
||||
expect(state.status, AuthStatus.loggedIn);
|
||||
expect(await PreferenceHelper.asyncPref.getBool(PREFS_HAS_EVER_SYNCED), true);
|
||||
});
|
||||
|
||||
test('token endpoint returns 500 → powerSyncUnreachable', () async {
|
||||
when(
|
||||
mockClient.get(tPowerSyncToken, headers: anyNamed('headers')),
|
||||
|
||||
@@ -16,15 +16,20 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:version/version.dart';
|
||||
import 'package:wger/core/consts.dart';
|
||||
import 'package:wger/core/network/auth_credential.dart';
|
||||
import 'package:wger/core/network/auth_credentials_storage.dart';
|
||||
import 'package:wger/core/network/secure_token_storage.dart';
|
||||
import 'package:wger/core/network/server_gating.dart';
|
||||
|
||||
import '../../fake_auth_environment.dart';
|
||||
|
||||
/// The version gates don't touch storage; this stand-in satisfies the
|
||||
/// constructor without pulling in secure-storage plumbing.
|
||||
class _FakeSecureTokenStorage extends Fake implements SecureTokenStorage {}
|
||||
@@ -35,6 +40,9 @@ ServerGating _gatingReturning(http.Response response) => ServerGating(
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
installFakeAuthEnvironment();
|
||||
|
||||
group('min server version check', () {
|
||||
final minVersion = Version.parse(MIN_SERVER_VERSION);
|
||||
final aboveMin = Version(minVersion.major, minVersion.minor + 1, 0).toString();
|
||||
@@ -129,4 +137,88 @@ void main() {
|
||||
expect(await gating.applicationUpdateRequired(serverUrl, '1.0.0'), true);
|
||||
});
|
||||
});
|
||||
|
||||
group('isPowerSyncReachable', () {
|
||||
const serverUrl = 'https://wger.example.com';
|
||||
const credential = AuthCredential.legacy('abc123');
|
||||
|
||||
/// Gating whose token endpoint answers [tokenBody] and whose liveness
|
||||
/// probes answer 200 only for [liveUrl]. Every requested URL is
|
||||
/// recorded in [requested].
|
||||
ServerGating gatingWithTokenResponse(
|
||||
Map<String, dynamic> tokenBody,
|
||||
String liveUrl,
|
||||
List<String> requested,
|
||||
) => ServerGating(
|
||||
MockClient((request) async {
|
||||
requested.add(request.url.toString());
|
||||
if (request.url.path.endsWith('/powersync-token')) {
|
||||
return http.Response(json.encode(tokenBody), 200);
|
||||
}
|
||||
if (request.url.toString() == liveUrl) {
|
||||
return http.Response('{"ready":true}', 200);
|
||||
}
|
||||
return http.Response('not found', 404);
|
||||
}),
|
||||
AuthCredentialsStorage(_FakeSecureTokenStorage()),
|
||||
);
|
||||
|
||||
test('probes the server-provided powersync_url', () async {
|
||||
final requested = <String>[];
|
||||
final gating = gatingWithTokenResponse(
|
||||
{'token': 't', 'powersync_url': 'https://ps.example.com'},
|
||||
'https://ps.example.com/probes/liveness',
|
||||
requested,
|
||||
);
|
||||
|
||||
expect(
|
||||
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
|
||||
true,
|
||||
);
|
||||
expect(requested, contains('https://ps.example.com/probes/liveness'));
|
||||
});
|
||||
|
||||
test('falls back to <serverUrl>/ps/ when powersync_url points at loopback', () async {
|
||||
final requested = <String>[];
|
||||
final gating = gatingWithTokenResponse(
|
||||
{'token': 't', 'powersync_url': 'http://localhost/ps/'},
|
||||
'$serverUrl/ps/probes/liveness',
|
||||
requested,
|
||||
);
|
||||
|
||||
expect(
|
||||
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
|
||||
true,
|
||||
);
|
||||
expect(requested, contains('$serverUrl/ps/probes/liveness'));
|
||||
});
|
||||
|
||||
test('falls back to <serverUrl>/ps/ when powersync_url is missing', () async {
|
||||
final requested = <String>[];
|
||||
final gating = gatingWithTokenResponse(
|
||||
{'token': 't'},
|
||||
'$serverUrl/ps/probes/liveness',
|
||||
requested,
|
||||
);
|
||||
|
||||
expect(
|
||||
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
|
||||
true,
|
||||
);
|
||||
expect(requested, contains('$serverUrl/ps/probes/liveness'));
|
||||
});
|
||||
|
||||
test('returns false when the resolved URL does not answer the probe', () async {
|
||||
final gating = gatingWithTokenResponse(
|
||||
{'token': 't', 'powersync_url': 'https://ps.example.com'},
|
||||
'https://somewhere-else.example.com/probes/liveness',
|
||||
<String>[],
|
||||
);
|
||||
|
||||
expect(
|
||||
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import 'dart:io';
|
||||
|
||||
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:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
@@ -167,9 +168,28 @@ void main() {
|
||||
});
|
||||
|
||||
group('fetchCredentials', () {
|
||||
/// Probe client answering 200 for any liveness probe, so the endpoint
|
||||
/// resolution keeps whatever URL the token response advertised.
|
||||
MockClient anyLivenessOk() => MockClient(
|
||||
(request) async => request.url.path.endsWith('/probes/liveness')
|
||||
? http.Response('{"ready":true}', 200)
|
||||
: http.Response('not found', 404),
|
||||
);
|
||||
|
||||
/// Probe client answering 200 only for [probeUrl].
|
||||
MockClient liveOnlyAt(String probeUrl) => MockClient(
|
||||
(request) async => request.url.toString() == probeUrl
|
||||
? http.Response('{"ready":true}', 200)
|
||||
: http.Response('not found', 404),
|
||||
);
|
||||
|
||||
test('builds PowerSyncCredentials with userId from sub and expiresAt from exp', () async {
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: anyLivenessOk(),
|
||||
);
|
||||
final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
|
||||
@@ -186,7 +206,11 @@ void main() {
|
||||
|
||||
test('coerces a numeric sub into a String (Django sends ints)', () async {
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: anyLivenessOk(),
|
||||
);
|
||||
final jwt = makeJwt({'sub': 42, 'exp': 1700000000});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
|
||||
@@ -199,7 +223,11 @@ void main() {
|
||||
|
||||
test('still produces credentials when JWT is opaque (userId/expiresAt null)', () async {
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: anyLivenessOk(),
|
||||
);
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': 'not.a.jwt', 'powersync_url': 'https://ps.example.com'},
|
||||
);
|
||||
@@ -212,6 +240,92 @@ void main() {
|
||||
expect(creds.expiresAt, isNull);
|
||||
});
|
||||
|
||||
test('falls back to <baseUrl>/ps/ when powersync_url does not answer the probe', () async {
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: liveOnlyAt('http://example.invalid/ps/probes/liveness'),
|
||||
);
|
||||
final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'http://localhost/ps/'},
|
||||
);
|
||||
|
||||
final creds = await connector.fetchCredentials();
|
||||
|
||||
expect(creds!.endpoint, 'http://example.invalid/ps/');
|
||||
});
|
||||
|
||||
test('falls back to <baseUrl>/ps/ when powersync_url is missing', () async {
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: liveOnlyAt('http://example.invalid/ps/probes/liveness'),
|
||||
);
|
||||
final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt},
|
||||
);
|
||||
|
||||
final creds = await connector.fetchCredentials();
|
||||
|
||||
expect(creds!.endpoint, 'http://example.invalid/ps/');
|
||||
});
|
||||
|
||||
test('probes once per powersync_url value, again when it changes', () async {
|
||||
final probes = <String>[];
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: MockClient((request) async {
|
||||
probes.add(request.url.toString());
|
||||
return http.Response('{"ready":true}', 200);
|
||||
}),
|
||||
);
|
||||
final jwt = makeJwt({'sub': 'u', 'exp': 1700000000});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
|
||||
);
|
||||
|
||||
await connector.fetchCredentials();
|
||||
await connector.fetchCredentials();
|
||||
expect(probes, ['https://ps.example.com/probes/liveness']);
|
||||
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'https://other.example.com'},
|
||||
);
|
||||
final creds = await connector.fetchCredentials();
|
||||
|
||||
expect(probes, hasLength(2));
|
||||
expect(creds!.endpoint, 'https://other.example.com');
|
||||
});
|
||||
|
||||
test('does not cache a failed resolution', () async {
|
||||
final probes = <String>[];
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: MockClient((request) async {
|
||||
probes.add(request.url.toString());
|
||||
return http.Response('not found', 404);
|
||||
}),
|
||||
);
|
||||
final jwt = makeJwt({'sub': 'u', 'exp': 1700000000});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
|
||||
);
|
||||
|
||||
expect(await connector.fetchCredentials(), isNull);
|
||||
expect(await connector.fetchCredentials(), isNull);
|
||||
|
||||
// Both candidates probed on both attempts: no negative caching.
|
||||
expect(probes, hasLength(4));
|
||||
});
|
||||
|
||||
test('returns null when the backend is unreachable', () async {
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
|
||||
@@ -224,7 +338,11 @@ void main() {
|
||||
|
||||
test('anchors expiresAt to the local clock via the token lifetime', () async {
|
||||
final mockApi = MockApiClient();
|
||||
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
|
||||
final connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: anyLivenessOk(),
|
||||
);
|
||||
// iat/exp lie far in the past; only their 600 s difference may matter.
|
||||
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
@@ -244,7 +362,11 @@ void main() {
|
||||
|
||||
setUp(() {
|
||||
mockApi = MockApiClient();
|
||||
connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
|
||||
connector = DjangoConnector(
|
||||
baseUrl: 'http://example.invalid',
|
||||
apiClient: mockApi,
|
||||
client: anyLivenessOk(),
|
||||
);
|
||||
records = [];
|
||||
final sub = Logger.root.onRecord.listen(records.add);
|
||||
addTearDown(sub.cancel);
|
||||
@@ -300,6 +422,23 @@ void main() {
|
||||
expect(infoLines('backend unreachable'), hasLength(2));
|
||||
});
|
||||
|
||||
test('logs the endpoint once, again only when it changes', () async {
|
||||
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
|
||||
);
|
||||
await connector.fetchCredentials();
|
||||
await connector.fetchCredentials();
|
||||
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
(_) async => {'token': jwt, 'powersync_url': 'https://other.example.com'},
|
||||
);
|
||||
await connector.fetchCredentials();
|
||||
|
||||
expect(infoLines('endpoint https://ps.example.com'), hasLength(1));
|
||||
expect(infoLines('endpoint https://other.example.com'), hasLength(1));
|
||||
});
|
||||
|
||||
test('does not log recovery when there was no outage', () async {
|
||||
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
|
||||
when(mockApi.getPowersyncToken()).thenAnswer(
|
||||
|
||||
Reference in New Issue
Block a user