Skip to content

Commit 5068b5e

Browse files
committed
msglist: Throttle fetchOlder retries
This approach is different from how a BackoffMachine is typically used, because the message list doesn't send and retry requests in a loop; its caller retries rapidly on scroll changes, and we want to ignore the excessive requests. The test drops irrelevant requests with `connection.takeRequests` without checking, as we are only interested in verifying that no request was sent. Fixes: #945 Signed-off-by: Zixuan James Li <[email protected]>
1 parent ef87fe4 commit 5068b5e

File tree

2 files changed

+85
-14
lines changed

2 files changed

+85
-14
lines changed

lib/model/message_list.dart

+54-13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import 'dart:async';
2+
13
import 'package:collection/collection.dart';
24
import 'package:flutter/foundation.dart';
35

6+
import '../api/backoff.dart';
47
import '../api/model/events.dart';
58
import '../api/model/model.dart';
69
import '../api/route/messages.dart';
@@ -89,9 +92,32 @@ mixin _MessageSequence {
8992
bool _haveOldest = false;
9093

9194
/// Whether we are currently fetching the next batch of older messages.
95+
///
96+
/// When this is true, [fetchOlder] is a no-op.
97+
/// That method is called frequently by Flutter's scrolling logic,
98+
/// and this field helps us avoid spamming the same request just to get
99+
/// the same response each time.
100+
///
101+
/// See also [fetchOlderCoolingDown].
92102
bool get fetchingOlder => _fetchingOlder;
93103
bool _fetchingOlder = false;
94104

105+
/// Whether [fetchOlder] had a request error recently.
106+
///
107+
/// When this is true, [fetchOlder] is a no-op.
108+
/// That method is called frequently by Flutter's scrolling logic,
109+
/// and this field mitigates spamming the same request and getting
110+
/// the same error each time.
111+
///
112+
/// "Recently" is decided by a [BackoffMachine] that resets
113+
/// when a [fetchOlder] request succeeds.
114+
///
115+
/// See also [fetchingOlder].
116+
bool get fetchOlderCoolingDown => _fetchOlderCoolingDown;
117+
bool _fetchOlderCoolingDown = false;
118+
119+
BackoffMachine? _fetchOlderCooldownBackoffMachine;
120+
95121
/// The parsed message contents, as a list parallel to [messages].
96122
///
97123
/// The i'th element is the result of parsing the i'th element of [messages].
@@ -107,7 +133,7 @@ mixin _MessageSequence {
107133
/// before, between, or after the messages.
108134
///
109135
/// This information is completely derived from [messages] and
110-
/// the flags [haveOldest] and [fetchingOlder].
136+
/// the flags [haveOldest], [fetchingOlder] and [fetchOlderCoolingDown].
111137
/// It exists as an optimization, to memoize that computation.
112138
final QueueList<MessageListItem> items = QueueList();
113139

@@ -241,6 +267,8 @@ mixin _MessageSequence {
241267
_fetched = false;
242268
_haveOldest = false;
243269
_fetchingOlder = false;
270+
_fetchOlderCoolingDown = false;
271+
_fetchOlderCooldownBackoffMachine = null;
244272
contents.clear();
245273
items.clear();
246274
}
@@ -289,10 +317,12 @@ mixin _MessageSequence {
289317
/// Update [items] to include markers at start and end as appropriate.
290318
void _updateEndMarkers() {
291319
assert(!(haveOldest && fetchingOlder));
292-
final startMarker = switch ((fetchingOlder, haveOldest)) {
293-
(true, _) => const MessageListLoadingItem(MessageListDirection.older),
294-
(_, true) => const MessageListHistoryStartItem(),
295-
(_, _) => null,
320+
assert(!(fetchingOlder && fetchOlderCoolingDown));
321+
final startMarker = switch ((fetchingOlder, haveOldest, fetchOlderCoolingDown)) {
322+
(true, _, _) => const MessageListLoadingItem(MessageListDirection.older),
323+
(_, true, _) => const MessageListHistoryStartItem(),
324+
(_, _, true) => const MessageListLoadingItem(MessageListDirection.older),
325+
(_, _, _) => null,
296326
};
297327
final hasStartMarker = switch (items.firstOrNull) {
298328
MessageListLoadingItem() => true,
@@ -469,7 +499,7 @@ class MessageListView with ChangeNotifier, _MessageSequence {
469499
Future<void> fetchInitial() async {
470500
// TODO(#80): fetch from anchor firstUnread, instead of newest
471501
// TODO(#82): fetch from a given message ID as anchor
472-
assert(!fetched && !haveOldest && !fetchingOlder);
502+
assert(!fetched && !haveOldest && !fetchingOlder && !fetchOlderCoolingDown);
473503
assert(messages.isEmpty && contents.isEmpty);
474504
// TODO schedule all this in another isolate
475505
final generation = this.generation;
@@ -497,20 +527,30 @@ class MessageListView with ChangeNotifier, _MessageSequence {
497527
Future<void> fetchOlder() async {
498528
if (haveOldest) return;
499529
if (fetchingOlder) return;
530+
if (fetchOlderCoolingDown) return;
500531
assert(fetched);
501532
assert(messages.isNotEmpty);
502533
_fetchingOlder = true;
503534
_updateEndMarkers();
504535
notifyListeners();
505536
final generation = this.generation;
506537
try {
507-
final result = await getMessages(store.connection,
508-
narrow: narrow.apiEncode(),
509-
anchor: NumericAnchor(messages[0].id),
510-
includeAnchor: false,
511-
numBefore: kMessageListFetchBatchSize,
512-
numAfter: 0,
513-
);
538+
final GetMessagesResult result;
539+
try {
540+
result = await getMessages(store.connection,
541+
narrow: narrow.apiEncode(),
542+
anchor: NumericAnchor(messages[0].id),
543+
includeAnchor: false,
544+
numBefore: kMessageListFetchBatchSize,
545+
numAfter: 0,
546+
);
547+
} catch (e) {
548+
assert(!fetchOlderCoolingDown);
549+
_fetchOlderCoolingDown = true;
550+
unawaited((_fetchOlderCooldownBackoffMachine ??= BackoffMachine())
551+
.wait().then((_) => _fetchOlderCoolingDown = false));
552+
rethrow;
553+
}
514554
if (this.generation > generation) return;
515555

516556
if (result.messages.isNotEmpty
@@ -528,6 +568,7 @@ class MessageListView with ChangeNotifier, _MessageSequence {
528568

529569
_insertAllMessages(0, fetchedMessages);
530570
_haveOldest = result.foundOldest;
571+
_fetchOlderCooldownBackoffMachine = null;
531572
} finally {
532573
if (this.generation == generation) {
533574
_fetchingOlder = false;

test/model/message_list_test.dart

+31-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'dart:convert';
33
import 'package:checks/checks.dart';
44
import 'package:http/http.dart' as http;
55
import 'package:test/scaffolding.dart';
6+
import 'package:zulip/api/exception.dart';
67
import 'package:zulip/api/model/events.dart';
78
import 'package:zulip/api/model/model.dart';
89
import 'package:zulip/api/model/narrow.dart';
@@ -236,6 +237,34 @@ void main() {
236237
..messages.length.equals(30);
237238
});
238239

240+
test('fetchOlder nop during backoff', () => awaitFakeAsync((async) async {
241+
final olderMessages = List.generate(5, (i) => eg.streamMessage());
242+
final initialMessages = List.generate(5, (i) => eg.streamMessage());
243+
await prepare(narrow: const CombinedFeedNarrow());
244+
await prepareMessages(foundOldest: false, messages: initialMessages);
245+
246+
connection.prepare(httpStatus: 400, json: {
247+
'result': 'error', 'code': 'BAD_REQUEST', 'msg': 'Bad request'});
248+
check(async.pendingTimers).isEmpty();
249+
await check(model.fetchOlder()).throws<ZulipApiException>();
250+
checkNotified(count: 2);
251+
check(model).fetchOlderCoolingDown.isTrue();
252+
253+
connection.takeRequests();
254+
await model.fetchOlder();
255+
checkNotNotified();
256+
check(model).fetchOlderCoolingDown.isTrue();
257+
check(model).fetchingOlder.isFalse();
258+
259+
async.flushTimers();
260+
check(model).fetchOlderCoolingDown.isFalse();
261+
262+
connection.prepare(json: olderResult(
263+
anchor: 1000, foundOldest: false, messages: olderMessages).toJson());
264+
await model.fetchOlder();
265+
checkNotified(count: 2);
266+
}));
267+
239268
test('fetchOlder handles servers not understanding includeAnchor', () async {
240269
const narrow = CombinedFeedNarrow();
241270
await prepare(narrow: narrow);
@@ -1791,7 +1820,7 @@ void checkInvariants(MessageListView model) {
17911820
if (model.haveOldest) {
17921821
check(model.items[i++]).isA<MessageListHistoryStartItem>();
17931822
}
1794-
if (model.fetchingOlder) {
1823+
if (model.fetchingOlder || model.fetchOlderCoolingDown) {
17951824
check(model.items[i++]).isA<MessageListLoadingItem>();
17961825
}
17971826
for (int j = 0; j < model.messages.length; j++) {
@@ -1847,6 +1876,7 @@ extension MessageListViewChecks on Subject<MessageListView> {
18471876
Subject<bool> get fetched => has((x) => x.fetched, 'fetched');
18481877
Subject<bool> get haveOldest => has((x) => x.haveOldest, 'haveOldest');
18491878
Subject<bool> get fetchingOlder => has((x) => x.fetchingOlder, 'fetchingOlder');
1879+
Subject<bool> get fetchOlderCoolingDown => has((x) => x.fetchOlderCoolingDown, 'fetchOlderCoolingDown');
18501880
}
18511881

18521882
/// A GetMessagesResult the server might return on an `anchor=newest` request.

0 commit comments

Comments
 (0)