mirror of
https://github.com/block/buzz.git
synced 2026-11-24 02:02:07 +00:00
perf(mobile): stop following presence for people no longer shown
Presence tracking now hands back a release. DM rows and profile sheets release on unmount, and people nobody has shown for 30 seconds leave the tracked set, the cache and the live subscription, which narrows to who is still on screen. With nobody shown the stream closes. Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Signed-off-by: Tom Brow <tomb@squareup.com>
This commit is contained in:
@@ -193,7 +193,7 @@ class _ChannelTile extends ConsumerWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _DmAvatar extends ConsumerWidget {
|
||||
class _DmAvatar extends HookConsumerWidget {
|
||||
final Channel channel;
|
||||
final String? currentPubkey;
|
||||
|
||||
@@ -209,6 +209,16 @@ class _DmAvatar extends ConsumerWidget {
|
||||
final visiblePubkeys = otherPubkeys.isNotEmpty
|
||||
? otherPubkeys
|
||||
: channel.participantPubkeys.map((pk) => pk.toLowerCase()).toList();
|
||||
final otherPubkey = visiblePubkeys.length == 1
|
||||
? visiblePubkeys.first
|
||||
: null;
|
||||
|
||||
// Presence is followed while this row is built; a list releases it when
|
||||
// the row scrolls away.
|
||||
useEffect(() {
|
||||
if (otherPubkey == null) return null;
|
||||
return ref.read(presenceCacheProvider.notifier).track([otherPubkey]);
|
||||
}, [otherPubkey]);
|
||||
|
||||
if (visiblePubkeys.length > 1) {
|
||||
return Container(
|
||||
@@ -232,7 +242,6 @@ class _DmAvatar extends ConsumerWidget {
|
||||
);
|
||||
}
|
||||
|
||||
final otherPubkey = visiblePubkeys.isNotEmpty ? visiblePubkeys.first : null;
|
||||
final profile = ref.watch(
|
||||
userCacheProvider.select(
|
||||
(profiles) => otherPubkey == null ? null : profiles[otherPubkey],
|
||||
@@ -245,11 +254,8 @@ class _DmAvatar extends ConsumerWidget {
|
||||
);
|
||||
|
||||
// Trigger fetches if not cached yet.
|
||||
if (otherPubkey != null) {
|
||||
if (profile == null) {
|
||||
ref.read(userCacheProvider.notifier).preload([otherPubkey]);
|
||||
}
|
||||
ref.read(presenceCacheProvider.notifier).track([otherPubkey]);
|
||||
if (otherPubkey != null && profile == null) {
|
||||
ref.read(userCacheProvider.notifier).preload([otherPubkey]);
|
||||
}
|
||||
|
||||
final avatarUrl = profile?.avatarUrl;
|
||||
|
||||
@@ -21,7 +21,16 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
/// Bound deduplication memory; redelivery must not re-arm confirmation.
|
||||
static const _seenIdLimit = 256;
|
||||
|
||||
/// How long a key nobody shows stays followed, so scrolling back and forth
|
||||
/// doesn't reopen the subscription on every row.
|
||||
static const releaseDelay = Duration(seconds: 30);
|
||||
|
||||
final Set<String> _tracked = {};
|
||||
// Widgets currently showing each key. A key with none is released, then
|
||||
// retired after [releaseDelay] unless shown again.
|
||||
final Map<String, int> _holders = {};
|
||||
final Set<String> _released = {};
|
||||
Timer? _retire;
|
||||
final Set<String> _pending = {};
|
||||
final Map<String, int> _revisions = {};
|
||||
final Map<String, int> _timestamps = {};
|
||||
@@ -53,7 +62,16 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
final scope = ref.watch(
|
||||
relayConfigProvider.select((config) => (config.baseUrl, config.nsec)),
|
||||
);
|
||||
if (_scope != scope) _tracked.clear();
|
||||
_retire?.cancel();
|
||||
_retire = null;
|
||||
_tracked.removeAll(_released);
|
||||
_released.clear();
|
||||
// A new community keeps only the keys still on screen.
|
||||
if (_scope != scope) {
|
||||
_tracked
|
||||
..clear()
|
||||
..addAll(_holders.keys);
|
||||
}
|
||||
_scope = scope;
|
||||
final generation = ++_generation;
|
||||
_epoch++;
|
||||
@@ -79,6 +97,8 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
_queued = null;
|
||||
_resubscribe?.cancel();
|
||||
_resubscribe = null;
|
||||
_retire?.cancel();
|
||||
_retire = null;
|
||||
});
|
||||
if (sessionState.status == SessionStatus.connected &&
|
||||
lifecycle == AppLifecycleState.resumed) {
|
||||
@@ -86,7 +106,7 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
// A replacement the relay never answered must not hold the slot, so a
|
||||
// lost REQ costs at most one poll interval.
|
||||
_abandonPending?.call();
|
||||
if (_presenceUnsub == null || !_subscribedKeys.containsAll(_tracked)) {
|
||||
if (_presenceUnsub == null || !_covered) {
|
||||
unawaited(_subscribe(generation));
|
||||
}
|
||||
// The snapshot backstop runs for a live stream even while a widening
|
||||
@@ -102,11 +122,16 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
return {};
|
||||
}
|
||||
|
||||
/// Request initial presence for exact keys. Repeated render calls coalesce.
|
||||
void track(List<String> pubkeys) {
|
||||
/// Follow presence for exact keys while they are shown. Call the returned
|
||||
/// function once when they no longer are.
|
||||
void Function() track(List<String> pubkeys) {
|
||||
final keys = {for (final key in pubkeys) key.trim().toLowerCase()}
|
||||
..remove('');
|
||||
var added = false;
|
||||
for (final key in pubkeys.map((key) => key.trim().toLowerCase())) {
|
||||
if (key.isNotEmpty && _tracked.add(key)) {
|
||||
for (final key in keys) {
|
||||
_holders[key] = (_holders[key] ?? 0) + 1;
|
||||
_released.remove(key);
|
||||
if (_tracked.add(key)) {
|
||||
_pending.add(key);
|
||||
added = true;
|
||||
}
|
||||
@@ -119,8 +144,48 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
} else {
|
||||
_schedule(_generation);
|
||||
}
|
||||
var released = false;
|
||||
return () {
|
||||
if (released) return;
|
||||
released = true;
|
||||
for (final key in keys) {
|
||||
final holders = (_holders[key] ?? 0) - 1;
|
||||
if (holders > 0) {
|
||||
_holders[key] = holders;
|
||||
} else {
|
||||
_holders.remove(key);
|
||||
_released.add(key);
|
||||
}
|
||||
}
|
||||
if (_released.isNotEmpty && ref.mounted) {
|
||||
_retire ??= Timer(releaseDelay, _retireReleased);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Stops following keys nobody has shown since their release, and narrows
|
||||
/// the live subscription to what is still shown.
|
||||
void _retireReleased() {
|
||||
_retire = null;
|
||||
if (!ref.mounted || _released.isEmpty) return;
|
||||
_tracked.removeAll(_released);
|
||||
_pending.removeAll(_released);
|
||||
for (final key in _released) {
|
||||
_timestamps.remove(key);
|
||||
_snapshotAt.remove(key);
|
||||
}
|
||||
// Absent means unknown: nothing keeps a retired key current.
|
||||
final kept = {
|
||||
for (final entry in state.entries)
|
||||
if (!_released.contains(entry.key)) entry.key: entry.value,
|
||||
};
|
||||
_released.clear();
|
||||
if (kept.length != state.length) state = kept;
|
||||
if (_poll?.isActive ?? false) _queueResubscribe(_generation);
|
||||
}
|
||||
|
||||
bool get _covered => setEquals(_subscribedKeys, _tracked);
|
||||
|
||||
void _queueResubscribe(int generation) {
|
||||
_resubscribe ??= Timer(Duration.zero, () {
|
||||
_resubscribe = null;
|
||||
@@ -149,12 +214,16 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
}
|
||||
|
||||
Future<void> _subscribe(int generation) async {
|
||||
if (_opening ||
|
||||
generation != _generation ||
|
||||
_tracked.isEmpty ||
|
||||
(_presenceUnsub != null && _subscribedKeys.containsAll(_tracked))) {
|
||||
if (_opening || generation != _generation) return;
|
||||
if (_tracked.isEmpty) {
|
||||
// Nobody is shown: close the stream, and the next track opens one.
|
||||
_presenceUnsub?.call();
|
||||
_presenceUnsub = null;
|
||||
_subscribedKeys.clear();
|
||||
_subscribeAttempted = _retrying = false;
|
||||
return;
|
||||
}
|
||||
if (_presenceUnsub != null && _covered) return;
|
||||
// One subscription opens at a time. A replacement holds this until it is
|
||||
// promoted or abandoned, so tracking bursts widen it in later rounds.
|
||||
_opening = true;
|
||||
@@ -185,7 +254,9 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
_abandonPending = null;
|
||||
_opening = false;
|
||||
final previous = _presenceUnsub;
|
||||
final added = keys.where((key) => !_subscribedKeys.contains(key));
|
||||
final added = keys.where(
|
||||
(key) => _tracked.contains(key) && !_subscribedKeys.contains(key),
|
||||
);
|
||||
_pending.addAll(added);
|
||||
_activeSubscription = subscription;
|
||||
_retrying = retrying;
|
||||
@@ -199,8 +270,8 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
_invalidateSnapshot();
|
||||
return;
|
||||
}
|
||||
// Keys tracked while this one opened need a wider subscription.
|
||||
if (!_subscribedKeys.containsAll(_tracked)) _queueResubscribe(generation);
|
||||
// Keys tracked or retired while this one opened need another one.
|
||||
if (!_covered) _queueResubscribe(generation);
|
||||
// Newly covered keys are read only now, so no change between an earlier
|
||||
// snapshot and their live coverage is lost.
|
||||
_schedule(generation);
|
||||
@@ -242,8 +313,8 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
_retrying = status == RelaySubscriptionStatus.retrying;
|
||||
_invalidateSnapshot();
|
||||
if (_retrying) return;
|
||||
// Keys tracked during the backoff need a wider subscription.
|
||||
if (!_subscribedKeys.containsAll(_tracked)) {
|
||||
// Keys tracked or retired during the backoff need another one.
|
||||
if (!_covered) {
|
||||
_queueResubscribe(generation);
|
||||
}
|
||||
_schedule(generation);
|
||||
@@ -340,7 +411,11 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
||||
}
|
||||
final updated = {...state};
|
||||
for (final key in keys) {
|
||||
if ((_revisions[key] ?? 0) != revisions[key]) continue;
|
||||
// A key retired meanwhile stays absent.
|
||||
if (!_tracked.contains(key) ||
|
||||
(_revisions[key] ?? 0) != revisions[key]) {
|
||||
continue;
|
||||
}
|
||||
if (events == null) {
|
||||
updated.remove(key); // failure is unknown; next poll retries
|
||||
} else {
|
||||
|
||||
@@ -154,10 +154,10 @@ class UserProfileSheet extends HookConsumerWidget {
|
||||
|
||||
// Ensure presence and status are tracked.
|
||||
useEffect(() {
|
||||
ref.read(presenceCacheProvider.notifier).track([pk]);
|
||||
final release = ref.read(presenceCacheProvider.notifier).track([pk]);
|
||||
ref.read(userStatusCacheProvider.notifier).track([pk]);
|
||||
ref.read(userCacheProvider.notifier).preload([pk]);
|
||||
return null;
|
||||
return release;
|
||||
}, [pk]);
|
||||
final copied = useState(false);
|
||||
final isOpeningDirectMessage = useState(false);
|
||||
|
||||
@@ -156,7 +156,7 @@ class _PresenceFixture extends PresenceCacheNotifier {
|
||||
@override
|
||||
Map<String, String> build() => {};
|
||||
@override
|
||||
void track(List<String> pubkeys) {}
|
||||
void Function() track(List<String> pubkeys) => () {};
|
||||
void setPresence(String? status) => state = {'alice': ?status};
|
||||
}
|
||||
|
||||
|
||||
@@ -266,6 +266,41 @@ void main() {
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('a DM row stops following presence once it is gone', (
|
||||
tester,
|
||||
) async {
|
||||
final relay = PresenceTestRelay();
|
||||
final channels = _FakeNotifier(testChannels);
|
||||
await tester.pumpWidget(
|
||||
buildTestable(
|
||||
overrides: [
|
||||
channelsProvider.overrideWith(() => channels),
|
||||
relaySessionProvider.overrideWith(() => relay),
|
||||
],
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
relay.results.removeAt(0).complete([
|
||||
presenceEvent('relay', 'online', subject: 'alice', timestamp: 20),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
final container = ProviderScope.containerOf(
|
||||
tester.element(_dmTileFor('Alice')),
|
||||
);
|
||||
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
||||
|
||||
channels.replaceChannels([
|
||||
for (final channel in testChannels)
|
||||
if (channel.channelType != 'dm') channel,
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Alice'), findsNothing);
|
||||
await tester.pump(PresenceCacheNotifier.releaseDelay);
|
||||
expect(relay.unsubscribes, 1);
|
||||
expect(container.read(presenceCacheProvider), isEmpty);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
for (final label in ['Channels options', 'Design options']) {
|
||||
testWidgets('$label exposes a labeled button and tap action', (
|
||||
tester,
|
||||
@@ -4200,6 +4235,8 @@ class _FakeNotifier extends ChannelsNotifier {
|
||||
@override
|
||||
Future<void> waitForUnreadCatchUp() async => await unreadCatchUp;
|
||||
|
||||
void replaceChannels(List<Channel> channels) => state = AsyncData(channels);
|
||||
|
||||
void addUnread(String channelId, ObservedUnreadEvent event) {
|
||||
(_observedEventsByChannel[channelId] ??= {})[event.id] = event;
|
||||
state = AsyncData([...state.requireValue]);
|
||||
|
||||
@@ -49,5 +49,5 @@ class _ListPresenceFixture extends PresenceCacheNotifier {
|
||||
@override
|
||||
Map<String, String> build() => {};
|
||||
@override
|
||||
void track(List<String> pubkeys) {}
|
||||
void Function() track(List<String> pubkeys) => () {};
|
||||
}
|
||||
|
||||
@@ -206,6 +206,112 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
test('a released key leaves the subscription once nobody shows it', () {
|
||||
fakeAsync((time) {
|
||||
final relaySession = _RecordingRelaySessionNotifier();
|
||||
final container = _buildContainer(relaySession: relaySession);
|
||||
addTearDown(container.dispose);
|
||||
final notifier = container.read(presenceCacheProvider.notifier);
|
||||
|
||||
container.read(presenceCacheProvider);
|
||||
// Alice is shown in two places, Bob in one.
|
||||
final aliceRow = notifier.track(['alice']);
|
||||
final aliceSheet = notifier.track(['alice']);
|
||||
final bobRow = notifier.track(['bob']);
|
||||
time.elapse(Duration.zero);
|
||||
expect(relaySession.subscriptions.last.filter.authors, ['alice', 'bob']);
|
||||
final wide = relaySession.subscriptions.last;
|
||||
|
||||
aliceRow();
|
||||
bobRow();
|
||||
bobRow(); // a second call releases nothing more
|
||||
time.elapse(
|
||||
PresenceCacheNotifier.releaseDelay - const Duration(seconds: 1),
|
||||
);
|
||||
expect(relaySession.subscriptions, [wide]);
|
||||
|
||||
time.elapse(const Duration(seconds: 1));
|
||||
expect(relaySession.subscriptions, hasLength(1));
|
||||
expect(relaySession.subscriptions.single.filter.authors, ['alice']);
|
||||
expect(container.read(presenceCacheProvider).keys, ['alice']);
|
||||
|
||||
relaySession.emit(_presence('bob', 'online'));
|
||||
relaySession.emit(_presence('alice', 'online'));
|
||||
expect(container.read(presenceCacheProvider), {'alice': 'online'});
|
||||
aliceSheet();
|
||||
});
|
||||
});
|
||||
|
||||
test('a key shown again within the delay keeps its subscription', () {
|
||||
fakeAsync((time) {
|
||||
final relaySession = _RecordingRelaySessionNotifier();
|
||||
final container = _buildContainer(relaySession: relaySession);
|
||||
addTearDown(container.dispose);
|
||||
final notifier = container.read(presenceCacheProvider.notifier);
|
||||
|
||||
container.read(presenceCacheProvider);
|
||||
notifier.track(['alice']);
|
||||
final bob = notifier.track(['bob']);
|
||||
time.elapse(Duration.zero);
|
||||
relaySession.emit(_presence('bob', 'online'));
|
||||
final wide = relaySession.subscriptions.single;
|
||||
|
||||
// Bob scrolls off and back before the delay ends.
|
||||
bob();
|
||||
time.elapse(const Duration(seconds: 10));
|
||||
notifier.track(['bob']);
|
||||
time.elapse(PresenceCacheNotifier.releaseDelay);
|
||||
expect(relaySession.subscriptions, [wide]);
|
||||
expect(container.read(presenceCacheProvider)['bob'], 'online');
|
||||
});
|
||||
});
|
||||
|
||||
test('releasing everyone closes the stream until someone is shown', () {
|
||||
fakeAsync((time) {
|
||||
final relaySession = _RecordingRelaySessionNotifier();
|
||||
final container = _buildContainer(relaySession: relaySession);
|
||||
addTearDown(container.dispose);
|
||||
final notifier = container.read(presenceCacheProvider.notifier);
|
||||
|
||||
container.read(presenceCacheProvider);
|
||||
final alice = notifier.track(['alice']);
|
||||
time.elapse(Duration.zero);
|
||||
alice();
|
||||
time.elapse(PresenceCacheNotifier.releaseDelay);
|
||||
expect(relaySession.subscriptions, isEmpty);
|
||||
expect(container.read(presenceCacheProvider), isEmpty);
|
||||
|
||||
relaySession.queried.clear();
|
||||
notifier.track(['carol']);
|
||||
time.elapse(Duration.zero);
|
||||
expect(relaySession.subscriptions.single.filter.authors, ['carol']);
|
||||
expect(relaySession.queried.expand((keys) => keys), ['carol']);
|
||||
});
|
||||
});
|
||||
|
||||
test('scrolling a long list keeps only the rows still shown', () {
|
||||
fakeAsync((time) {
|
||||
final relaySession = _RecordingRelaySessionNotifier();
|
||||
final container = _buildContainer(relaySession: relaySession);
|
||||
addTearDown(container.dispose);
|
||||
final notifier = container.read(presenceCacheProvider.notifier);
|
||||
|
||||
container.read(presenceCacheProvider);
|
||||
// 500 rows scroll past a window of 10.
|
||||
final shown = <void Function()>[];
|
||||
for (var row = 0; row < 500; row++) {
|
||||
shown.add(notifier.track(['p${row.toString().padLeft(3, '0')}']));
|
||||
if (shown.length > 10) shown.removeAt(0)();
|
||||
time.elapse(const Duration(milliseconds: 50));
|
||||
}
|
||||
time.elapse(PresenceCacheNotifier.releaseDelay);
|
||||
expect(relaySession.subscriptions, hasLength(1));
|
||||
expect(relaySession.subscriptions.single.filter.authors, [
|
||||
for (var row = 490; row < 500; row++) 'p$row',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
test('the poll still reads a live stream while its widening fails', () {
|
||||
fakeAsync((time) {
|
||||
final relaySession = _RecordingRelaySessionNotifier();
|
||||
|
||||
@@ -200,7 +200,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
test('community/account switch clears tracking and fences old snapshot', () {
|
||||
test('community/account switch keeps shown keys and fences old snapshot', () {
|
||||
scenario((time, container, relay) {
|
||||
final stale = relay.results.removeAt(0);
|
||||
container
|
||||
@@ -211,13 +211,41 @@ void main() {
|
||||
stale.complete([presenceEvent('alice', 'online')]);
|
||||
time.flushMicrotasks();
|
||||
expect(container.read(presenceCacheProvider), isEmpty);
|
||||
expect(relay.queries, hasLength(1));
|
||||
// Alice and Bob are still on screen, so the new community reads them.
|
||||
expect(relay.queries, hasLength(2));
|
||||
expect(relay.queries.last.authors, ['alice', 'bob']);
|
||||
relay.results.removeAt(0).complete([]);
|
||||
time.flushMicrotasks();
|
||||
container.read(presenceCacheProvider.notifier).track(['carol']);
|
||||
time.elapse(Duration.zero);
|
||||
expect(relay.queries.last.authors, ['carol']);
|
||||
});
|
||||
});
|
||||
|
||||
test('a key retired during its snapshot stays absent', () {
|
||||
fakeAsync((time) {
|
||||
final relay = PresenceTestRelay();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
relaySessionProvider.overrideWith(() => relay),
|
||||
appLifecycleProvider.overrideWith(_Lifecycle.new),
|
||||
],
|
||||
);
|
||||
final release = container.read(presenceCacheProvider.notifier).track([
|
||||
'alice',
|
||||
]);
|
||||
time.elapse(Duration.zero);
|
||||
final snapshot = relay.results.removeAt(0);
|
||||
release();
|
||||
time.elapse(PresenceCacheNotifier.releaseDelay);
|
||||
snapshot.complete([presenceEvent('alice', 'online')]);
|
||||
time.flushMicrotasks();
|
||||
expect(container.read(presenceCacheProvider), isEmpty);
|
||||
container.dispose();
|
||||
time.flushMicrotasks();
|
||||
});
|
||||
});
|
||||
|
||||
test('background stops polling; foreground obtains a fresh snapshot', () {
|
||||
scenario((time, container, relay) {
|
||||
relay.results.removeAt(0).complete([presenceEvent('alice', 'online')]);
|
||||
|
||||
Reference in New Issue
Block a user