Skip to content

Commit 3f789d1

Browse files
committed
perf(mobile): subscribe to presence only for people on screen
The presence cache subscribed to every kind:20001 heartbeat in the community and dropped the ones it wasn't tracking. On Block's Builderlab that is about 27 events a second, roughly 3 MB every 5 minutes (35 MB an hour) while the app is open, each one decoded and verified, to show presence for a few DM partners and open profiles. Subscribe with `authors` set to the tracked keys instead. Tracking a new key replaces the subscription with a wider one, opening the new one before closing the old, and reads the new key's snapshot once the subscription covers it. With nothing tracked there is no subscription. Signed-off-by: Tom Brow <[email protected]>
1 parent 3c0adc1 commit 3f789d1

2 files changed

Lines changed: 88 additions & 12 deletions

File tree

‎mobile/lib/features/profile/presence_cache_provider.dart‎

Lines changed: 69 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,16 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
2727
final Map<String, int> _timestamps = {};
2828
final Map<String, int> _snapshotAt = {};
2929
final List<String> _seenIds = [];
30+
// Keys the live subscription asks for. Only tracked keys are subscribed:
31+
// a community's presence heartbeats arrive many times a second.
32+
final Set<String> _subscribedKeys = {};
3033
void Function()? _presenceUnsub;
3134
Timer? _poll;
3235
Timer? _queued;
36+
Timer? _resubscribe;
37+
int _nextSubscription = 0;
38+
int _activeSubscription = 0;
39+
bool _subscribeAttempted = false;
3340
int _generation = 0;
3441
int _epoch = 0;
3542
bool _querying = false;
@@ -53,6 +60,9 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
5360
_timestamps.clear();
5461
_snapshotAt.clear();
5562
_seenIds.clear();
63+
_subscribedKeys.clear();
64+
_activeSubscription = 0;
65+
_subscribeAttempted = false;
5666
_pending
5767
..clear()
5868
..addAll(_tracked);
@@ -63,11 +73,13 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
6373
_poll?.cancel();
6474
_queued?.cancel();
6575
_queued = null;
76+
_resubscribe?.cancel();
77+
_resubscribe = null;
6678
});
6779
if (sessionState.status == SessionStatus.connected &&
6880
lifecycle == AppLifecycleState.resumed) {
6981
_poll = Timer.periodic(const Duration(seconds: 60), (_) {
70-
if (_presenceUnsub == null) {
82+
if (_presenceUnsub == null || !_subscribedKeys.containsAll(_tracked)) {
7183
unawaited(_subscribe(generation));
7284
} else if (!_querying) {
7385
_pending.addAll(_tracked);
@@ -82,10 +94,32 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
8294

8395
/// Request initial presence for exact keys. Repeated render calls coalesce.
8496
void track(List<String> pubkeys) {
97+
var added = false;
8598
for (final key in pubkeys.map((key) => key.trim().toLowerCase())) {
86-
if (key.isNotEmpty && _tracked.add(key)) _pending.add(key);
99+
if (key.isNotEmpty && _tracked.add(key)) {
100+
_pending.add(key);
101+
added = true;
102+
}
103+
}
104+
// While live (the poll runs only then), new keys are read once the
105+
// subscription covers them, so no live event falls between the snapshot
106+
// and the subscription.
107+
if (added && (_poll?.isActive ?? false)) {
108+
_queueResubscribe(_generation);
109+
} else {
110+
_schedule(_generation);
87111
}
88-
_schedule(_generation);
112+
}
113+
114+
void _queueResubscribe(int generation) {
115+
_resubscribe ??= Timer(Duration.zero, () {
116+
_resubscribe = null;
117+
// Without a subscription, the next poll opens one with every key.
118+
if (generation == _generation &&
119+
(_presenceUnsub != null || !_subscribeAttempted)) {
120+
unawaited(_subscribe(generation));
121+
}
122+
});
89123
}
90124

91125
void _schedule(int generation) {
@@ -105,39 +139,64 @@ class PresenceCacheNotifier extends Notifier<Map<String, String>> {
105139
}
106140

107141
Future<void> _subscribe(int generation) async {
108-
if (_opening || generation != _generation) return;
142+
if (_opening ||
143+
generation != _generation ||
144+
_tracked.isEmpty ||
145+
(_presenceUnsub != null && _subscribedKeys.containsAll(_tracked))) {
146+
return;
147+
}
109148
_opening = true;
110-
_retrying = false;
149+
_subscribeAttempted = true;
150+
final keys = _tracked.toList()..sort();
151+
final subscription = ++_nextSubscription;
111152
var closed = false;
153+
// The subscription being replaced keeps delivering until this one opens.
154+
bool current() =>
155+
generation == _generation &&
156+
!closed &&
157+
subscription == _activeSubscription;
112158
try {
113159
final unsub = await ref
114160
.read(relaySessionProvider.notifier)
115161
.subscribeWithStatus(
116-
const NostrFilter(kinds: [EventKind.presenceUpdate], limit: 0),
162+
NostrFilter(
163+
kinds: const [EventKind.presenceUpdate],
164+
authors: keys,
165+
limit: 0,
166+
),
117167
(event) {
118-
if (generation == _generation && !closed && !_retrying) {
119-
_handlePresenceEvent(event);
120-
}
168+
if (current() && !_retrying) _handlePresenceEvent(event);
121169
},
122170
onStatusChanged: (status) {
123-
if (generation != _generation || closed) return;
171+
if (!current()) return;
124172
_retrying = status == RelaySubscriptionStatus.retrying;
125173
_invalidateSnapshot();
126174
if (!_retrying) _schedule(generation);
127175
},
128176
onClosed: (_) {
129177
if (generation != _generation || closed) return;
130178
closed = true;
179+
if (subscription != _activeSubscription) return;
131180
_presenceUnsub?.call();
132181
_presenceUnsub = null;
182+
_subscribedKeys.clear();
133183
_invalidateSnapshot();
134184
},
135185
);
136186
if (generation != _generation || closed) {
137187
unsub();
138188
return;
139189
}
190+
final previous = _presenceUnsub;
191+
_activeSubscription = subscription;
192+
_retrying = false;
140193
_presenceUnsub = unsub;
194+
_subscribedKeys
195+
..clear()
196+
..addAll(keys);
197+
previous?.call();
198+
// Keys tracked while this one opened need a wider subscription.
199+
if (!_subscribedKeys.containsAll(_tracked)) _queueResubscribe(generation);
141200
_schedule(generation);
142201
} catch (error) {
143202
if (generation == _generation) {

‎mobile/test/features/profile/presence_cache_provider_test.dart‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ void main() {
1717

1818
// Track alice, then emit her initial 'online' status.
1919
container.read(presenceCacheProvider.notifier).track(['alice']);
20+
await _pumpEventQueue();
2021
relaySession.emit(_presence('alice', 'online'));
2122
expect(container.read(presenceCacheProvider)['alice'], 'online');
2223

@@ -35,6 +36,7 @@ void main() {
3536

3637
// Track only alice.
3738
container.read(presenceCacheProvider.notifier).track(['alice']);
39+
await _pumpEventQueue();
3840

3941
// Emit event for bob (untracked).
4042
relaySession.emit(_presence('bob', 'online'));
@@ -52,6 +54,7 @@ void main() {
5254
await _pumpEventQueue();
5355

5456
container.read(presenceCacheProvider.notifier).track(['alice']);
57+
await _pumpEventQueue();
5558
relaySession.emit(_presence('alice', 'online'));
5659
expect(container.read(presenceCacheProvider)['alice'], 'online');
5760

@@ -71,6 +74,7 @@ void main() {
7174
await _pumpEventQueue();
7275

7376
container.read(presenceCacheProvider.notifier).track(['alice']);
77+
await _pumpEventQueue();
7478
relaySession.emit(_presence('alice', 'online'));
7579

7680
// Listen for state changes after initial setup.
@@ -84,18 +88,30 @@ void main() {
8488
expect(stateChangeCount, 0);
8589
});
8690

87-
test('subscribes to kind:20001 with limit 0', () async {
91+
test('subscribes to kind:20001 for tracked pubkeys only', () async {
8892
final relaySession = _RecordingRelaySessionNotifier();
8993
final container = _buildContainer(relaySession: relaySession);
9094
addTearDown(container.dispose);
9195

9296
container.read(presenceCacheProvider);
9397
await _pumpEventQueue();
98+
// Nothing is tracked, so nothing is worth a community-wide stream.
99+
expect(relaySession.filters, isEmpty);
94100

95-
// Should have subscribed with the correct filter.
101+
container.read(presenceCacheProvider.notifier).track(['alice']);
102+
await _pumpEventQueue();
96103
expect(relaySession.filters, hasLength(1));
97104
expect(relaySession.filters.single.kinds, [EventKind.presenceUpdate]);
105+
expect(relaySession.filters.single.authors, ['alice']);
98106
expect(relaySession.filters.single.limit, 0);
107+
108+
// A newly tracked key replaces the subscription with a wider one.
109+
container.read(presenceCacheProvider.notifier).track(['bob', 'alice']);
110+
await _pumpEventQueue();
111+
expect(relaySession.filters, hasLength(1));
112+
expect(relaySession.filters.single.authors, ['alice', 'bob']);
113+
relaySession.emit(_presence('bob', 'online'));
114+
expect(container.read(presenceCacheProvider)['bob'], 'online');
99115
});
100116

101117
test('WS event uses pubkey variable, not literal string', () async {
@@ -112,6 +128,7 @@ void main() {
112128
'deadbeef',
113129
'cafebabe',
114130
]);
131+
await _pumpEventQueue();
115132

116133
// Seed cafebabe -> offline, then set deadbeef online.
117134
relaySession.emit(_presence('cafebabe', 'offline'));

0 commit comments

Comments
 (0)