TF-5022 Await the websocket refreshes of MailboxController and ThreadController through awaitShownAccountState, which drops a stale result but still ends a dead session, and skip a folder change queued before a switch

This commit is contained in:
dab246 committed 2026-11-13 10:01:57 +07:00
1 parent d859db1806
commit 7e11d74519
7 files changed
+255 -49

No files matched your search

@@ -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 = <ShownAccountStateSubscription>{};
SwitchAttemptStamp stampShownAccountRequest() => SwitchAttemptStamp(activeAccountSource);
SwitchAttemptStamp _stampShownAccountRequest() => SwitchAttemptStamp(activeAccountSource);
/// Drops what arrives once its switch attempt ended or this controller closed.
ShownAccountStateSubscription consumeShownAccountState(Stream<Either<Failure, Success>> 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<Either<Failure, Success>> awaitShownAccountState(Stream<Either<Failure, Success>> viewResults) async {
final stamp = _stampShownAccountRequest();
final Either<Failure, Success> 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<Failure, Success>? 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<Either<Failure, Success>> 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';
}
@@ -8,6 +8,7 @@ import 'package:tmail_ui_user/features/delegation/presentation/bridge/switch_att
typedef OnViewResult = void Function(Either<Failure, Success> viewResult);
typedef OnViewError = void Function(dynamic error, StackTrace stackTrace);
typedef OnViewDone = void Function();
typedef OnStaleViewResult = void Function({Either<Failure, Success>? 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<Either<Failure, Success>>? _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<Either<Failure, Success>> viewResults) {
@@ -41,12 +45,18 @@ class ShownAccountStateSubscription {
}
void _handleData(Either<Failure, Success> 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);
}
@@ -627,15 +627,15 @@ class MailboxController extends BaseMailboxController
}
Future<void> _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<RefreshChangesAllMailboxSuccess>();
@@ -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) {
@@ -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<void> _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<Either<Failure, Success>?> _refreshChangeListEmailCache(
SwitchAttemptStamp stamp, {
bool collapseThreads = false,
}) async {
final refreshState = await _refreshChangesEmailsInMailboxInteractor.execute(
Future<Either<Failure, Success>> _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<void> _refreshChangeListEmail(SwitchAttemptStamp stamp) async {
Future<void> _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<RefreshChangesAllEmailSuccess>();
@@ -983,15 +974,15 @@ class ThreadController extends BaseController
}
}
Future<void> _refreshChangeListEmailsInVirtualFolder(SwitchAttemptStamp stamp) async {
Future<void> _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);
@@ -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 = <Either<Failure, Success>>[];
final errors = <Object>[];
final urgentErrors = <Object?>[];
int doneCount = 0;
@override
void onData(Either<Failure, Success> 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<Either<Failure, Success>?> awaitLoad(Future<Either<Failure, Success>> 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<Either<Failure, Success>> viewResults) arrive,
List<Object> urgentErrors,
});
const _badCredentials = BadCredentialsException();
final _refreshTokenFailed = RefreshTokenFailedException();
final _staleResult = (
arrival: 'a result',
arrive: (StreamController<Either<Failure, Success>> viewResults) => viewResults.add(Right(_Loaded())),
urgentErrors: <Object>[],
);
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<Object> 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<Either<Failure, Success>> viewResults;
late _Reader reader;
setUp(() {
source = ActiveAccountSourceFixtures.putShowing(DelegationFixtures.aliceAccountId);
viewResults = StreamController<Either<Failure, Success>>();
reader = _Reader();
});
test('returns the last result while its attempt is current', () async {
final pending = reader.awaitLoad(reader.awaitShownAccountState(viewResults.stream));
final last = Right<Failure, Success>(_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<Either<Failure, Success>> retry;
@@ -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<Either<Failure, Success>>();
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 {
@@ -192,22 +192,34 @@ Future<void> pumpLocalizedApp(WidgetTester tester) async {
await tester.pump();
}
/// Keeps the errors that reach the view, which [MailboxController] only logs.
class ErrorRecordingMailboxController extends MailboxController {
final viewErrors = <Object>[];
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));