From b4f05adf9b4da18daeef22008fbf981d61856434 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 18 Nov 2026 13:33:31 -0800 Subject: [PATCH] fix(mobile): read before a switch changes anything and keep subscriber throws visible without a destination A community switch read the saved list after saving the new active ID, so a failed read left the disk on the new community and every retry returned early. It now reads first. With no reporting destination, the subscriber guard swallowed the error that used to fail the test that hit it and print in development. The no-op reporter now hands subscriber errors to the zone as uncaught. Also: report an invalid OK rejection with no pending publish, throw a new error object for each new report so Sentry does not drop repeats, and correct the spec's status and out-of-scope lines. Co-authored-by: studio Signed-off-by: Tom Brow --- docs/mobile-diagnostic-reporting.md | 4 +- .../shared/community/community_provider.dart | 10 +- .../diagnostics/diagnostic_reporter.dart | 11 +- .../lib/shared/hosted/builderlab_account.dart | 3 +- .../lib/shared/relay/relay_closed_policy.dart | 3 +- mobile/lib/shared/relay/relay_session.dart | 2 +- .../shared/relay/relay_session_delivery.dart | 2 +- .../community/community_provider_test.dart | 44 +++++ .../test/shared/relay/relay_session_test.dart | 154 +++++++++++------- 9 files changed, 164 insertions(+), 69 deletions(-) diff --git a/docs/mobile-diagnostic-reporting.md b/docs/mobile-diagnostic-reporting.md index 1941bc50b9..f9b8e4827b 100644 --- a/docs/mobile-diagnostic-reporting.md +++ b/docs/mobile-diagnostic-reporting.md @@ -1,6 +1,6 @@ # Mobile diagnostic reporting -Status: step one in progress. Implemented: the reporting module and explicit error reports. Still to come: networking counts. +Status: step one in progress. Implemented: the reporting module and explicit error reports (for push, the relay's capability descriptor; push gateway replies are not reported yet). Still to come: networking counts. Terminology is defined in [CONTEXT.md](../CONTEXT.md#mobile-builds). The decisions behind this spec are in [ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md) and [ADR 0008](adr/0008-sentry-for-mobile-diagnostic-reporting.md). @@ -74,7 +74,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - Alert rules, dashboards and the destination's own configuration, which belong to whoever owns the destination. - Diagnostic reporting in a [public build](../CONTEXT.md#public-build). Nothing prevents it, but what a report carries was chosen for internal builds. Turning it on there first needs the member's public key and the server host names removed, the rest of the list reviewed, and a way to tell people ([ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md)). Because identity and every attribute pass through one module, that is a small code change. - Usage or behavior data of any kind, beyond the SDK's session records described above. -- Fixing the bugs the reports will reveal, including two found while planning: one subscriber that throws can lose the rest of a batch of events, and a catch-all in account requests presents every error as an outage. +- Fixing the bugs the reports will reveal, including one found while planning: a catch-all in account requests presents every error as an outage. ## Further notes diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart index 85ea0e294e..849819d979 100644 --- a/mobile/lib/shared/community/community_provider.dart +++ b/mobile/lib/shared/community/community_provider.dart @@ -524,11 +524,15 @@ class CommunityListNotifier extends AsyncNotifier> { final storage = ref.read(communityStorageProvider); final activeId = await storage.loadActiveId(); if (activeId == id) return; + // From storage: while the list reloads (after sign-in, say), state can + // still hold the previous list. Read before anything changes, so a + // failed read leaves the switch to retry. + final target = (await storage.loadAll()) + .where((c) => c.id == id) + .firstOrNull; await ref.read(communityTransitionProvider).run(); await storage.saveActiveId(id); - // From storage: while the list reloads (after sign-in, say), state can - // still hold the previous list. - _reportAs((await storage.loadAll()).where((c) => c.id == id).firstOrNull); + _reportAs(target); // Reassign list state to trigger activeCommunityProvider (which watches // communityListProvider.future) to rebuild and pick up the new active ID. // We can't use ref.invalidate(activeCommunityProvider) here because that diff --git a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart index 61a2c40794..1fd66e8c78 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:hooks_riverpod/hooks_riverpod.dart'; /// The one interface app code uses for diagnostic reporting. @@ -89,7 +91,14 @@ class NoopDiagnosticReporter implements DiagnosticReporter { Object error, StackTrace? stackTrace, { required DiagnosticOperation operation, - }) {} + }) { + // A throwing subscriber is a bug in the app, and the delivery guard + // catches it. With no destination, surface it the way an uncaught throw + // would: it fails the test that hit it and prints in development. + if (operation == DiagnosticOperation.eventSubscriber) { + Zone.current.handleUncaughtError(error, stackTrace ?? StackTrace.current); + } + } @override void countNetworkEvent(NetworkEvent event) {} diff --git a/mobile/lib/shared/hosted/builderlab_account.dart b/mobile/lib/shared/hosted/builderlab_account.dart index 59e7b5318a..a64d412e4f 100644 --- a/mobile/lib/shared/hosted/builderlab_account.dart +++ b/mobile/lib/shared/hosted/builderlab_account.dart @@ -663,7 +663,8 @@ class BuilderlabAccountClient { try { value = jsonDecode(utf8.decode(response.bodyBytes)); if (value is! Map) { - throw const FormatException('account response is not an object'); + // Not const: Sentry drops a repeat of the last error object. + throw FormatException('account response is not an object'); } } on FormatException catch (error, stackTrace) { _diagnostics.reportError( diff --git a/mobile/lib/shared/relay/relay_closed_policy.dart b/mobile/lib/shared/relay/relay_closed_policy.dart index 2680f1e214..97d72dc378 100644 --- a/mobile/lib/shared/relay/relay_closed_policy.dart +++ b/mobile/lib/shared/relay/relay_closed_policy.dart @@ -47,8 +47,9 @@ bool isRelayDeadlineError(Object error) { /// Reported when the relay says a request the app sent is invalid. It never /// reaches callers, and it carries no relay text: the reason is free text. +/// Not const: Sentry drops a repeat of the last error object. class RelayInvalidRequest implements Exception { - const RelayInvalidRequest(); + RelayInvalidRequest(); @override String toString() => 'RelayInvalidRequest'; diff --git a/mobile/lib/shared/relay/relay_session.dart b/mobile/lib/shared/relay/relay_session.dart index 4fbc31043c..b3a40da37f 100644 --- a/mobile/lib/shared/relay/relay_session.dart +++ b/mobile/lib/shared/relay/relay_session.dart @@ -1008,10 +1008,10 @@ class RelaySessionNotifier extends Notifier { ? data[3] as String : ''; + if (!accepted) _reportInvalidRequest(message); final pending = _pendingEvents.remove(eventId); if (pending == null) return; pending.timeout.cancel(); - if (!accepted) _reportInvalidRequest(message); if (accepted) { // We don't have the full event here; create a minimal placeholder. diff --git a/mobile/lib/shared/relay/relay_session_delivery.dart b/mobile/lib/shared/relay/relay_session_delivery.dart index ea34d4f7c6..6b5d3e483e 100644 --- a/mobile/lib/shared/relay/relay_session_delivery.dart +++ b/mobile/lib/shared/relay/relay_session_delivery.dart @@ -55,7 +55,7 @@ extension _RelaySessionDelivery on RelaySessionNotifier { void _reportInvalidRequest(String message) { if (!isInvalidRequestRejection(message)) return; _diagnostics.reportError( - const RelayInvalidRequest(), + RelayInvalidRequest(), StackTrace.current, operation: DiagnosticOperation.relayRejection, ); diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index 2a241aa24c..e4459c5716 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -962,6 +962,35 @@ void main() { expect(reporter.member, keys.public); }); + test('a switch whose read fails changes nothing and can retry', () async { + final storage = _FailingLoadStorage(fakeSecure); + communityStorage = storage; + container = createContainer(); + final notifier = container.read(communityListProvider.notifier); + final a = Community.create( + name: 'A', + relayUrl: 'https://a.example.com', + nsec: nostr.Keys.generate().nsec, + ); + final b = Community.create( + name: 'B', + relayUrl: 'https://b.example.com', + nsec: nostr.Keys.generate().nsec, + ); + await container.read(communityListProvider.future); + await notifier.addCommunity(a); + await notifier.addCommunity(b); + await notifier.switchCommunity(a.id); + + storage.failNextLoad = true; + await expectLater(notifier.switchCommunity(b.id), throwsStateError); + expect(await storage.loadActiveId(), a.id); + + await notifier.switchCommunity(b.id); + expect(await storage.loadActiveId(), b.id); + expect((await container.read(activeCommunityProvider.future))?.id, b.id); + }); + group('activeCommunityProvider', () { test('returns null when no communities', () async { container = createContainer(); @@ -1046,3 +1075,18 @@ class _MemberRecorder extends NoopDiagnosticReporter { @override void setMember(String? pubkey) => member = pubkey; } + +class _FailingLoadStorage extends CommunityStorage { + _FailingLoadStorage(FlutterSecureStorage secure) : super(secure: secure); + + bool failNextLoad = false; + + @override + Future> loadAll() { + if (failNextLoad) { + failNextLoad = false; + throw StateError('keychain read failed'); + } + return super.loadAll(); + } +} diff --git a/mobile/test/shared/relay/relay_session_test.dart b/mobile/test/shared/relay/relay_session_test.dart index 4b9ee4aadd..b4414f4bb8 100644 --- a/mobile/test/shared/relay/relay_session_test.dart +++ b/mobile/test/shared/relay/relay_session_test.dart @@ -1334,68 +1334,11 @@ void main() { test( 'a subscriber that throws is reported and the rest of its batch still arrives', () async { - final sockets = <_ControlledRelaySocket>[]; - final keychain = nostr.Keys.generate(); - final auth = _ReloadingAuthNotifier()..pubkey = keychain.public; final reporter = _RecordingDiagnostics(); - final session = RelaySessionNotifier( - socketFactory: - ({ - required wsUrl, - required nsec, - required onMessage, - required onConnected, - required onDisconnected, - }) { - final socket = _ControlledRelaySocket( - wsUrl: wsUrl, - nsec: nsec, - onMessage: onMessage, - onConnected: onConnected, - onDisconnected: onDisconnected, - ); - sockets.add(socket); - return socket; - }, - ); - final container = ProviderContainer( - overrides: [ - relaySessionProvider.overrideWith(() => session), - relayConfigProvider.overrideWith( - () => _FakeRelayConfigNotifier( - baseUrl: 'https://relay.example', - nsec: keychain.nsec, - ), - ), - authProvider.overrideWith(() => auth), - diagnosticReporterProvider.overrideWithValue(reporter), - ], - ); - addTearDown(container.dispose); - await container.read(authProvider.future); - final listener = container.listen(relaySessionProvider, (_, _) {}); - addTearDown(listener.close); - await Future.delayed(Duration.zero); - sockets.single.connectSuccessfully(); - final delivered = []; - final subscribed = session.subscribe(_channelFilter, (event) { - if (event.id == 'event-1') throw StateError('handler bug'); - delivered.add(event.id); - }); - await Future.delayed(Duration.zero); - final subId = sockets.single.sent.single[1]; - session.debugHandleSocketMessageForTest(['EOSE', subId]); - await subscribed; + final flush = await _batchWithThrowingSubscriber(reporter, delivered); - for (final id in ['event-1', 'event-2']) { - session.debugHandleSocketMessageForTest([ - 'EVENT', - subId, - _event(id: id).toJson(), - ]); - } - session.debugFlushEventBuffer(); + flush(); expect(delivered, ['event-2']); expect(reporter.errors, [ @@ -1404,6 +1347,23 @@ void main() { }, ); + test( + 'with no destination, a throwing subscriber surfaces as uncaught and the batch still arrives', + () async { + final delivered = []; + final flush = await _batchWithThrowingSubscriber( + const NoopDiagnosticReporter(), + delivered, + ); + final uncaught = []; + + runZonedGuarded(flush, (error, _) => uncaught.add(error)); + + expect(delivered, ['event-2']); + expect(uncaught, [isA()]); + }, + ); + test('delivers the same live event to each matching subscription', () async { final session = RelaySessionNotifier(); final firstEvents = []; @@ -2361,10 +2321,18 @@ void main() { ]); await expectLater(invalid, throwsA(isA())); session.debugHandleMessage(['CLOSED', 'sub-1', 'invalid: bad filter']); + // No pending publish, as for a typing indicator or a reply after timeout. + session.debugHandleMessage([ + 'OK', + 'event-3', + false, + 'invalid: bad signature', + ]); expect(reporter.errors, [ (RelayInvalidRequest, DiagnosticOperation.relayRejection), (RelayInvalidRequest, DiagnosticOperation.relayRejection), + (RelayInvalidRequest, DiagnosticOperation.relayRejection), ]); }); } @@ -2656,3 +2624,71 @@ class _RecordingDiagnostics extends NoopDiagnosticReporter { required DiagnosticOperation operation, }) => errors.add((error.runtimeType, operation)); } + +/// Subscribes a handler that throws on `event-1` and buffers `event-1` and +/// `event-2`. Returns the flush that delivers them. +Future _batchWithThrowingSubscriber( + DiagnosticReporter reporter, + List delivered, +) async { + final sockets = <_ControlledRelaySocket>[]; + final keychain = nostr.Keys.generate(); + final auth = _ReloadingAuthNotifier()..pubkey = keychain.public; + final session = RelaySessionNotifier( + socketFactory: + ({ + required wsUrl, + required nsec, + required onMessage, + required onConnected, + required onDisconnected, + }) { + final socket = _ControlledRelaySocket( + wsUrl: wsUrl, + nsec: nsec, + onMessage: onMessage, + onConnected: onConnected, + onDisconnected: onDisconnected, + ); + sockets.add(socket); + return socket; + }, + ); + final container = ProviderContainer( + overrides: [ + relaySessionProvider.overrideWith(() => session), + relayConfigProvider.overrideWith( + () => _FakeRelayConfigNotifier( + baseUrl: 'https://relay.example', + nsec: keychain.nsec, + ), + ), + authProvider.overrideWith(() => auth), + diagnosticReporterProvider.overrideWithValue(reporter), + ], + ); + addTearDown(container.dispose); + await container.read(authProvider.future); + final listener = container.listen(relaySessionProvider, (_, _) {}); + addTearDown(listener.close); + await Future.delayed(Duration.zero); + sockets.single.connectSuccessfully(); + + final subscribed = session.subscribe(_channelFilter, (event) { + if (event.id == 'event-1') throw StateError('handler bug'); + delivered.add(event.id); + }); + await Future.delayed(Duration.zero); + final subId = sockets.single.sent.single[1]; + session.debugHandleSocketMessageForTest(['EOSE', subId]); + await subscribed; + + for (final id in ['event-1', 'event-2']) { + session.debugHandleSocketMessageForTest([ + 'EVENT', + subId, + _event(id: id).toJson(), + ]); + } + return session.debugFlushEventBuffer; +}