diff --git a/lib/features/delegation/presentation/bridge/active_account_reader.dart b/lib/features/delegation/presentation/bridge/active_account_reader.dart index 8b42e22bb..76dd86794 100644 --- a/lib/features/delegation/presentation/bridge/active_account_reader.dart +++ b/lib/features/delegation/presentation/bridge/active_account_reader.dart @@ -8,6 +8,7 @@ import 'package:tmail_ui_user/features/base/base_controller.dart'; import 'package:tmail_ui_user/features/delegation/presentation/bridge/active_account_source.dart'; import 'package:tmail_ui_user/features/delegation/presentation/bridge/shown_account_state_subscription.dart'; import 'package:tmail_ui_user/features/delegation/presentation/bridge/switch_attempt_stamp.dart'; +import 'package:tmail_ui_user/main/exceptions/remote/authentication_exception.dart'; /// For a GetX class that reads the shown mailbox. Settings and other personal areas use my own /// account and never mix it in. See ADR-0114. @@ -24,15 +25,16 @@ mixin ActiveAccountReader { mixin ShownAccountStateConsumer on BaseController, ActiveAccountReader { final _shownAccountSubscriptions = {}; - SwitchAttemptStamp stampShownAccountRequest() => SwitchAttemptStamp(activeAccountSource); + SwitchAttemptStamp _stampShownAccountRequest() => SwitchAttemptStamp(activeAccountSource); /// Drops what arrives once its switch attempt ended or this controller closed. ShownAccountStateSubscription consumeShownAccountState(Stream> viewResults) { final subscription = ShownAccountStateSubscription( - stamp: stampShownAccountRequest(), + stamp: _stampShownAccountRequest(), onData: onData, onError: onError, onDone: onDone, + onStale: _reportEndedSession, onEnded: _shownAccountSubscriptions.remove, ); _shownAccountSubscriptions.add(subscription); @@ -40,11 +42,43 @@ mixin ShownAccountStateConsumer on BaseController, ActiveAccountReader { return subscription; } + /// The last result of [viewResults]. Once its switch attempt ended, a result or an error throws + /// [_ShownAccountChanged] instead, which stops the caller and [onError] drops. + Future> awaitShownAccountState(Stream> viewResults) async { + final stamp = _stampShownAccountRequest(); + final Either viewResult; + try { + viewResult = await viewResults.last; + } catch (error) { + if (stamp.isCurrent) rethrow; + _reportEndedSession(error: error); + throw const _ShownAccountChanged(); + } + if (stamp.isCurrent) return viewResult; + _reportEndedSession(viewResult: viewResult); + throw const _ShownAccountChanged(); + } + + @override + void onError(dynamic error, StackTrace stackTrace) { + if (error is _ShownAccountChanged) return; + super.onError(error, stackTrace); + } + + /// A dead session ends every account, so a stale result still logs out on it. + void _reportEndedSession({Either? viewResult, Object? error}) { + final staleError = error ?? + viewResult?.fold((failure) => failure is FeatureFailure ? failure.exception : null, (_) => null); + if (staleError is AuthenticationException && validateUrgentException(staleError)) { + handleUrgentException(exception: staleError); + } + } + /// The retry stream is bound to the account of the failed request, so a tap after its attempt /// ended only closes the toast. @override VoidCallback retryActionOf(Stream> retry) { - final stamp = stampShownAccountRequest(); + final stamp = _stampShownAccountRequest(); return () { if (stamp.isCurrent) consumeShownAccountState(retry); }; @@ -59,3 +93,11 @@ mixin ShownAccountStateConsumer on BaseController, ActiveAccountReader { super.onClose(); } } + +/// Thrown by [ShownAccountStateConsumer.awaitShownAccountState] in place of a stale result. +class _ShownAccountChanged implements Exception { + const _ShownAccountChanged(); + + @override + String toString() => 'ShownAccountChanged'; +} diff --git a/lib/features/delegation/presentation/bridge/shown_account_state_subscription.dart b/lib/features/delegation/presentation/bridge/shown_account_state_subscription.dart index e1709a149..73a4cb6ed 100644 --- a/lib/features/delegation/presentation/bridge/shown_account_state_subscription.dart +++ b/lib/features/delegation/presentation/bridge/shown_account_state_subscription.dart @@ -8,6 +8,7 @@ import 'package:tmail_ui_user/features/delegation/presentation/bridge/switch_att typedef OnViewResult = void Function(Either viewResult); typedef OnViewError = void Function(dynamic error, StackTrace stackTrace); typedef OnViewDone = void Function(); +typedef OnStaleViewResult = void Function({Either? viewResult, Object? error}); typedef OnSubscriptionEnded = void Function(ShownAccountStateSubscription subscription); class ShownAccountStateSubscription { @@ -15,6 +16,7 @@ class ShownAccountStateSubscription { final OnViewResult _onData; final OnViewError _onError; final OnViewDone _onDone; + final OnStaleViewResult _onStale; final OnSubscriptionEnded _onEnded; StreamSubscription>? _subscription; @@ -25,10 +27,12 @@ class ShownAccountStateSubscription { required OnViewResult onData, required OnViewError onError, required OnViewDone onDone, + required OnStaleViewResult onStale, required OnSubscriptionEnded onEnded, }) : _onData = onData, _onError = onError, _onDone = onDone, + _onStale = onStale, _onEnded = onEnded; void listen(Stream> viewResults) { @@ -41,12 +45,18 @@ class ShownAccountStateSubscription { } void _handleData(Either viewResult) { - if (_cancelIfStale()) return; + if (_cancelIfStale()) { + _onStale(viewResult: viewResult); + return; + } _onData(viewResult); } void _handleError(Object error, StackTrace stackTrace) { - if (_cancelIfStale()) return; + if (_cancelIfStale()) { + _onStale(error: error); + return; + } _onError(error, stackTrace); } diff --git a/lib/features/mailbox/presentation/mailbox_controller.dart b/lib/features/mailbox/presentation/mailbox_controller.dart index 407a56769..401722fb6 100644 --- a/lib/features/mailbox/presentation/mailbox_controller.dart +++ b/lib/features/mailbox/presentation/mailbox_controller.dart @@ -627,15 +627,15 @@ class MailboxController extends BaseMailboxController } Future _handleWebSocketMessage(WebSocketMessage message) async { - final stamp = stampShownAccountRequest(); + // An account switch clears the folder state it leaves, so a message queued before it has nothing to refresh. + if (currentMailboxState == null) return; try { - final refreshViewState = await refreshAllMailboxInteractor!.execute( + final refreshViewState = await awaitShownAccountState(refreshAllMailboxInteractor!.execute( session!, accountId!, currentMailboxState!, properties: MailboxConstants.propertiesDefault, - ).last; - if (!stamp.isCurrent) return; + )); final refreshState = refreshViewState .foldSuccessWithResult(); @@ -650,7 +650,6 @@ class MailboxController extends BaseMailboxController } } catch (e, stackTrace) { logWarning('MailboxController::_processMailboxStateQueue:Error processing state: $e'); - if (!stamp.isCurrent) return; onError(e, stackTrace); } if (currentMailboxState != null) { diff --git a/lib/features/thread/presentation/thread_controller.dart b/lib/features/thread/presentation/thread_controller.dart index 9eab0d7b8..392fb5250 100644 --- a/lib/features/thread/presentation/thread_controller.dart +++ b/lib/features/thread/presentation/thread_controller.dart @@ -19,7 +19,6 @@ import 'package:jmap_dart_client/jmap/mail/mailbox/mailbox.dart'; import 'package:model/model.dart'; import 'package:tmail_ui_user/features/base/base_controller.dart'; import 'package:tmail_ui_user/features/delegation/presentation/bridge/active_account_reader.dart'; -import 'package:tmail_ui_user/features/delegation/presentation/bridge/switch_attempt_stamp.dart'; import 'package:tmail_ui_user/features/email/domain/model/mark_read_action.dart'; import 'package:tmail_ui_user/features/email/domain/state/delete_email_permanently_state.dart'; import 'package:tmail_ui_user/features/email/domain/state/delete_multiple_emails_permanently_state.dart'; @@ -896,18 +895,17 @@ class ThreadController extends BaseController Future _handleWebSocketMessage(WebSocketMessage message) async { // An account switch clears the email state it leaves, so a message queued before it has nothing to refresh. if (mailboxDashBoardController.currentEmailState == null) return; - final stamp = stampShownAccountRequest(); try { if (searchController.isSearchEmailRunning && PlatformInfo.isWeb) { - await _refreshChangeListEmailCache(stamp); + await _refreshChangeListEmailCache(); } else if (selectedMailbox?.isVirtualFolder == true) { - await _refreshChangeListEmailsInVirtualFolder(stamp); + await _refreshChangeListEmailsInVirtualFolder(); } else { - await _refreshChangeListEmail(stamp); + await _refreshChangeListEmail(); } } catch (e, stackTrace) { logWarning('ThreadController::_handleWebSocketMessage:Error processing state: $e'); - if (stamp.isCurrent) onError(e, stackTrace); + onError(e, stackTrace); } finally { if (mailboxDashBoardController.currentEmailState != null) { _webSocketQueueHandler?.removeMessagesUpToCurrent( @@ -916,12 +914,8 @@ class ThreadController extends BaseController } } - /// Null once [stamp] is stale, so the changes of an ended attempt never apply. - Future?> _refreshChangeListEmailCache( - SwitchAttemptStamp stamp, { - bool collapseThreads = false, - }) async { - final refreshState = await _refreshChangesEmailsInMailboxInteractor.execute( + Future> _refreshChangeListEmailCache({bool collapseThreads = false}) async { + final refreshState = await awaitShownAccountState(_refreshChangesEmailsInMailboxInteractor.execute( _session!, _accountId!, mailboxDashBoardController.currentEmailState!, @@ -938,8 +932,7 @@ class ThreadController extends BaseController ), emailFilter: getEmailFilterForLoadMailbox(), collapseThreads: collapseThreads, - ).last; - if (!stamp.isCurrent) return null; + )); refreshState.fold( (failure) {}, @@ -953,7 +946,7 @@ class ThreadController extends BaseController return refreshState; } - Future _refreshChangeListEmail(SwitchAttemptStamp stamp) async { + Future _refreshChangeListEmail() async { log('ThreadController::_refreshChangeListEmail:'); final collapseThreads = shouldCollapseThreads; // A refresh replaces the list from the top, which shifts pages counted by @@ -963,10 +956,8 @@ class ThreadController extends BaseController if (holdLoadMore) _holdLoadMoreForRefresh(); try { final refreshViewState = await _refreshChangeListEmailCache( - stamp, collapseThreads: collapseThreads, ); - if (refreshViewState == null) return; final refreshState = refreshViewState .foldSuccessWithResult(); @@ -983,15 +974,15 @@ class ThreadController extends BaseController } } - Future _refreshChangeListEmailsInVirtualFolder(SwitchAttemptStamp stamp) async { + Future _refreshChangeListEmailsInVirtualFolder() async { log('ThreadController::_refreshChangeListEmailsInVirtualFolder:'); // The refresh replaces the whole list, so a page appended meanwhile would // be overwritten. Load-more waits for it and runs once it has landed. _holdLoadMoreForRefresh(); try { - if (await _refreshChangeListEmailCache(stamp) == null) return; + await _refreshChangeListEmailCache(); - final viewState = await _getEmailsInMailboxInteractor + final viewState = await awaitShownAccountState(_getEmailsInMailboxInteractor .execute( _session!, _accountId!, @@ -1009,9 +1000,7 @@ class ThreadController extends BaseController useCache: false, forceEmailQuery: shouldCollapseThreads, collapseThreads: shouldCollapseThreads, - ) - .last; - if (!stamp.isCurrent) return; + )); dispatchState(viewState); diff --git a/test/features/delegation/presentation/bridge/active_account_reader_test.dart b/test/features/delegation/presentation/bridge/active_account_reader_test.dart index 22b7ea526..8a764162f 100644 --- a/test/features/delegation/presentation/bridge/active_account_reader_test.dart +++ b/test/features/delegation/presentation/bridge/active_account_reader_test.dart @@ -8,6 +8,8 @@ import 'package:get/get.dart'; import 'package:tmail_ui_user/features/base/base_controller.dart'; import 'package:tmail_ui_user/features/delegation/presentation/bridge/active_account_reader.dart'; import 'package:tmail_ui_user/features/delegation/presentation/notifier/active_account_notifier.dart'; +import 'package:tmail_ui_user/main/exceptions/remote/authentication_exception.dart'; +import 'package:tmail_ui_user/main/exceptions/remote/network_exception.dart'; import '../../../../fixtures/active_account_source_fixtures.dart'; import '../../../../fixtures/base_controller_fixtures.dart'; @@ -16,20 +18,78 @@ import '../../../../fixtures/delegation_fixtures.dart'; class _Reader extends BaseController with ActiveAccountReader, ShownAccountStateConsumer { final results = >[]; final errors = []; + final urgentErrors = []; int doneCount = 0; @override void onData(Either newState) => results.add(newState); @override - void onError(dynamic error, StackTrace stackTrace) => errors.add(error); + void handleErrorViewState(Object error, StackTrace stackTrace) => errors.add(error); + + @override + void handleUrgentException({Failure? failure, Exception? exception}) => urgentErrors.add(exception); @override void onDone() => doneCount++; + + /// Runs [pending] the way a controller awaits a load: an error goes to [onError]. + Future?> awaitLoad(Future> pending) async { + try { + return await pending; + } catch (error, stackTrace) { + onError(error, stackTrace); + return null; + } + } } class _Loaded extends UIState {} +class _LoadFailure extends FeatureFailure { + _LoadFailure(dynamic exception) : super(exception: exception); +} + +typedef _StaleArrival = ({ + String arrival, + void Function(StreamController> viewResults) arrive, + List urgentErrors, +}); + +const _badCredentials = BadCredentialsException(); +final _refreshTokenFailed = RefreshTokenFailedException(); + +final _staleResult = ( + arrival: 'a result', + arrive: (StreamController> viewResults) => viewResults.add(Right(_Loaded())), + urgentErrors: [], +); + +final List<_StaleArrival> _staleArrivals = [ + ( + arrival: 'an error', + arrive: (viewResults) => viewResults.addError(StateError('late failure')), + urgentErrors: [], + ), + ( + arrival: 'a connection error', + arrive: (viewResults) => viewResults.addError(const ConnectionError()), + urgentErrors: [], + ), + ( + arrival: 'a session failure', + arrive: (viewResults) => viewResults.add(Left(_LoadFailure(_badCredentials))), + urgentErrors: [_badCredentials], + ), + ( + arrival: 'a session error', + arrive: (viewResults) => viewResults.addError(_refreshTokenFailed), + urgentErrors: [_refreshTokenFailed], + ), +]; + +String _staleOutcome(List urgentErrors) => urgentErrors.isEmpty ? 'is dropped' : 'still ends the session'; + void main() { setUp(BaseControllerFixtures.registerDependencies); tearDown(Get.reset); @@ -154,6 +214,20 @@ void main() { expect(reader.doneCount, 0); }); + for (final (:arrival, :arrive, :urgentErrors) in _staleArrivals) { + test('$arrival that arrives once another account is shown ${_staleOutcome(urgentErrors)}', () async { + reader.consumeShownAccountState(viewResults.stream); + source.show(DelegationFixtures.bobAccountId); + + arrive(viewResults); + await pumpEventQueue(); + + expect(reader.results, isEmpty); + expect(reader.errors, isEmpty); + expect(reader.urgentErrors, urgentErrors); + }); + } + test('a closed reader gets no more results', () async { reader.consumeShownAccountState(viewResults.stream); @@ -166,6 +240,57 @@ void main() { }); }); + group('awaitShownAccountState:', () { + late FakeActiveAccountSource source; + late StreamController> viewResults; + late _Reader reader; + + setUp(() { + source = ActiveAccountSourceFixtures.putShowing(DelegationFixtures.aliceAccountId); + viewResults = StreamController>(); + reader = _Reader(); + }); + + test('returns the last result while its attempt is current', () async { + final pending = reader.awaitLoad(reader.awaitShownAccountState(viewResults.stream)); + final last = Right(_Loaded()); + + viewResults + ..add(Right(_Loaded())) + ..add(last); + await viewResults.close(); + + expect(await pending, last); + expect(reader.errors, isEmpty); + }); + + test('throws an error to the caller while its attempt is current', () async { + final pending = reader.awaitLoad(reader.awaitShownAccountState(viewResults.stream)); + final error = StateError('load failed'); + + viewResults.addError(error); + await viewResults.close(); + + expect(await pending, isNull); + expect(reader.errors, [error]); + }); + + for (final (:arrival, :arrive, :urgentErrors) in [..._staleArrivals, _staleResult]) { + test('$arrival that arrives once another account is shown stops the caller and ${_staleOutcome(urgentErrors)}', + () async { + final pending = reader.awaitLoad(reader.awaitShownAccountState(viewResults.stream)); + source.show(DelegationFixtures.bobAccountId); + + arrive(viewResults); + await viewResults.close(); + + expect(await pending, isNull); + expect(reader.errors, isEmpty); + expect(reader.urgentErrors, urgentErrors); + }); + } + }); + group('retryActionOf:', () { late FakeActiveAccountSource source; late StreamController> retry; diff --git a/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_shown_account_test.dart b/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_shown_account_test.dart index c186be4f7..3cd21b2cf 100644 --- a/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_shown_account_test.dart +++ b/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_shown_account_test.dart @@ -226,6 +226,35 @@ void main() { expect(mailboxController.currentMailboxState, isNull); }); + test('a folder change queued before another account is shown never runs once the folder state is cleared', () async { + final myChanges = StreamController>(); + when(refreshAllMailboxInteractor.execute(any, any, any, properties: anyNamed('properties'))) + .thenAnswer((_) => myChanges.stream); + clearInteractions(refreshAllMailboxInteractor); + final source = ActiveAccountSourceFixtures.putShowing(testAccountId); + final controller = newMailboxController()..onInit(); + mailboxController = controller; + controller.currentMailboxState = State('alice-state'); + mailboxDashboardController.dispatchMailboxUIAction( + RefreshChangeMailboxAction(newState: State('alice-new-state'))); + await pumpEventQueue(); + mailboxDashboardController.dispatchMailboxUIAction( + RefreshChangeMailboxAction(newState: State('alice-newer-state'))); + await pumpEventQueue(); + + source.show(DelegationFixtures.bobAccountId); + myChanges.add(Right(RefreshChangesAllMailboxSuccess( + mailboxList: [], + currentMailboxState: State('alice-refreshed-state'), + ))); + await myChanges.close(); + await pumpEventQueue(); + + verify(refreshAllMailboxInteractor.execute(any, any, any, properties: anyNamed('properties'))).called(1); + expect(controller.viewErrors, isEmpty); + expect(controller.currentMailboxState, isNull); + }); + for (final switched in [false, true]) { testWidgets('a failed folder changes refresh ${switched ? 'of an account shown before shows no error' : 'shows its error'}', (tester) async { diff --git a/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_test_harness.dart b/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_test_harness.dart index d1cd796eb..4d90cbeb9 100644 --- a/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_test_harness.dart +++ b/test/features/mailbox_dashboard/presentation/controller/mailbox_dashboard_controller_test_harness.dart @@ -192,22 +192,34 @@ Future pumpLocalizedApp(WidgetTester tester) async { await tester.pump(); } +/// Keeps the errors that reach the view, which [MailboxController] only logs. +class ErrorRecordingMailboxController extends MailboxController { + final viewErrors = []; + + ErrorRecordingMailboxController(TreeBuilder mailboxTreeBuilder) + : super( + createNewMailboxInteractor, + deleteMultipleMailboxInteractor, + renameMailboxInteractor, + moveMailboxInteractor, + subscribeMailboxInteractor, + subscribeMultipleMailboxInteractor, + subaddressingInteractor, + createDefaultMailboxInteractor, + moveFolderContentInteractor, + mailboxTreeBuilder, + verifyNameInteractor, + getAllMailboxInteractor, + refreshAllMailboxInteractor, + ); + + @override + void handleErrorViewState(Object error, StackTrace stackTrace) => viewErrors.add(error); +} + /// onInit schedules onReady for the next frame, so a test that calls it never calls onReady too. -MailboxController newMailboxController({TreeBuilder? mailboxTreeBuilder}) => MailboxController( - createNewMailboxInteractor, - deleteMultipleMailboxInteractor, - renameMailboxInteractor, - moveMailboxInteractor, - subscribeMailboxInteractor, - subscribeMultipleMailboxInteractor, - subaddressingInteractor, - createDefaultMailboxInteractor, - moveFolderContentInteractor, - mailboxTreeBuilder ?? treeBuilder, - verifyNameInteractor, - getAllMailboxInteractor, - refreshAllMailboxInteractor, - ); +ErrorRecordingMailboxController newMailboxController({TreeBuilder? mailboxTreeBuilder}) => + ErrorRecordingMailboxController(mailboxTreeBuilder ?? treeBuilder); void setUpMailboxDashboardControllerTest() { setUp(() => ActiveAccountSourceFixtures.putShowing(null));