Skip to content

Commit 2572c55

Browse files
committed
perf(mobile): verify profile batches off the UI isolate
Signed-off-by: Tom Brow <[email protected]>
1 parent 4cd82f5 commit 2572c55

3 files changed

Lines changed: 440 additions & 55 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import 'dart:isolate';
2+
3+
import '../crypto/nip_oa.dart';
4+
import '../relay/nostr_models.dart';
5+
import 'user_profile.dart';
6+
7+
/// A verified profile together with its NIP-01 replacement order.
8+
typedef ParsedProfileEvent = ({
9+
UserProfile profile,
10+
int createdAt,
11+
String eventId,
12+
});
13+
14+
/// Parses and verifies profile history without blocking the UI isolate.
15+
///
16+
/// Capture only the event batch here, never a provider or its surrounding
17+
/// context. NIP-OA verification performs synchronous elliptic-curve work.
18+
Future<List<ParsedProfileEvent>> parseProfileEventBatch(
19+
List<NostrEvent> events,
20+
) => Isolate.run(() => _parseBatch(events));
21+
22+
List<ParsedProfileEvent> _parseBatch(List<NostrEvent> events) {
23+
final latest = <String, NostrEvent>{};
24+
for (final event in events) {
25+
if (event.kind != 0) continue;
26+
final pubkey = event.pubkey.toLowerCase();
27+
final current = latest[pubkey];
28+
if (current == null ||
29+
event.createdAt > current.createdAt ||
30+
(event.createdAt == current.createdAt &&
31+
event.id.compareTo(current.id) < 0)) {
32+
latest[pubkey] = event;
33+
}
34+
}
35+
return [for (final event in latest.values) parseProfileEvent(event)];
36+
}
37+
38+
/// Parses a single live profile, including its verified owner attribution.
39+
ParsedProfileEvent parseProfileEvent(NostrEvent event) {
40+
final data = ProfileData.fromEvent(event);
41+
return (
42+
profile: UserProfile(
43+
pubkey: data.pubkey.toLowerCase(),
44+
displayName: data.displayName,
45+
avatarUrl: data.avatarUrl,
46+
about: data.about,
47+
nip05Handle: data.nip05,
48+
ownerPubkey: verifiedOaOwnerPubkey(event.tags, event.pubkey),
49+
),
50+
createdAt: event.createdAt,
51+
eventId: event.id,
52+
);
53+
}

‎mobile/lib/shared/profile/user_cache_provider.dart‎

Lines changed: 93 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import 'dart:async';
33
import 'package:hooks_riverpod/hooks_riverpod.dart';
44

55
import '../community/community_provider.dart';
6-
import '../crypto/nip_oa.dart';
76
import '../push/push_presentation_cache.dart';
87
import '../relay/relay.dart';
98
import 'user_profile.dart';
9+
import 'profile_event_parser.dart';
1010

1111
/// In-memory cache of user profiles, fetched in batches from the relay.
1212
///
@@ -15,14 +15,20 @@ import 'user_profile.dart';
1515
class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
1616
final Set<String> _pending = {};
1717
final Map<String, ({int createdAt, String eventId})> _profileEventOrders = {};
18+
int _generation = 0;
19+
bool _flushInFlight = false;
20+
Future<void> _verificationQueue = Future.value();
1821
Timer? _batchTimer;
1922
Completer<bool>? _batchCompleter;
2023

2124
@override
2225
Map<String, UserProfile> build() {
2326
ref.watch(relayConfigProvider);
27+
_generation++;
2428
_profileEventOrders.clear();
2529
ref.onDispose(() {
30+
_generation++;
31+
_pending.clear();
2632
_batchTimer?.cancel();
2733
_batchTimer = null;
2834
_batchCompleter?.complete(false);
@@ -57,7 +63,7 @@ class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
5763
if (uncached.isEmpty && !alreadyPending) return Future.value(true);
5864
_pending.addAll(uncached);
5965
final completer = _batchCompleter ??= Completer<bool>();
60-
_batchTimer ??= Timer(const Duration(milliseconds: 50), _flushPending);
66+
_scheduleBatch();
6167
return completer.future;
6268
}
6369

@@ -72,23 +78,14 @@ class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
7278
.toSet()
7379
.toList();
7480
if (normalized.isEmpty) return true;
81+
final generation = _generation;
7582
try {
7683
final session = ref.read(relaySessionProvider.notifier);
7784
final events = await session.fetchHistory(
7885
NostrFilters.profilesBatch(normalized),
7986
);
80-
final updated = Map<String, UserProfile>.from(state);
81-
final updatedOrders = Map<String, ({int createdAt, String eventId})>.from(
82-
_profileEventOrders,
83-
);
84-
for (final event in events) {
85-
_cacheProfileEvent(event, updated, updatedOrders);
86-
}
87-
_profileEventOrders
88-
..clear()
89-
..addAll(updatedOrders);
90-
state = updated;
91-
return true;
87+
if (!_isCurrent(generation)) return false;
88+
return await _verifyAndMerge(events, generation);
9289
} catch (_) {
9390
return false;
9491
}
@@ -108,7 +105,7 @@ class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
108105
if (state.containsKey(pubkey) || _pending.contains(pubkey)) return;
109106
_pending.add(pubkey);
110107
_batchCompleter ??= Completer<bool>();
111-
_batchTimer ??= Timer(const Duration(milliseconds: 50), _flushPending);
108+
_scheduleBatch();
112109
}
113110

114111
Future<void> _flushPending() async {
@@ -120,6 +117,8 @@ class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
120117
final completer = _batchCompleter;
121118
_batchCompleter = null;
122119

120+
_flushInFlight = true;
121+
final generation = _generation;
123122
var succeeded = false;
124123
try {
125124
final communityID = ref.read(activeCommunityProvider).value?.id;
@@ -128,18 +127,8 @@ class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
128127
NostrFilters.profilesBatch(pubkeys),
129128
);
130129

131-
final updated = Map<String, UserProfile>.from(state);
132-
final updatedOrders = Map<String, ({int createdAt, String eventId})>.from(
133-
_profileEventOrders,
134-
);
135-
for (final event in events) {
136-
_cacheProfileEvent(event, updated, updatedOrders);
137-
}
138-
139-
_profileEventOrders
140-
..clear()
141-
..addAll(updatedOrders);
142-
state = updated;
130+
if (!_isCurrent(generation)) return;
131+
if (!await _verifyAndMerge(events, generation)) return;
143132
if (communityID != null) {
144133
unawaited(cacheBuzzPushProfileEvents(communityID, events));
145134
}
@@ -148,43 +137,92 @@ class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
148137
// Silently fail — non-gating callers will just show pubkeys.
149138
} finally {
150139
completer?.complete(succeeded);
140+
_flushInFlight = false;
141+
if (ref.mounted && _pending.isNotEmpty) _scheduleBatch();
151142
}
152143
}
153144

154-
bool _cacheProfileEvent(
155-
NostrEvent event,
156-
Map<String, UserProfile> profiles, [
157-
Map<String, ({int createdAt, String eventId})>? orders,
158-
]) {
145+
void _scheduleBatch() {
146+
if (_flushInFlight) return;
147+
_batchTimer ??= Timer(const Duration(milliseconds: 50), _flushPending);
148+
}
149+
150+
Future<bool> _verifyAndMerge(List<NostrEvent> events, int generation) {
151+
// Both refresh and preload share one worker slot. Keep this queue across
152+
// community changes so an old worker cannot overlap a new community's job.
153+
final result = _verificationQueue.then((_) async {
154+
if (!_isCurrent(generation)) return false;
155+
// Match live-cache admission before parsing. In particular, a malformed
156+
// stale profile must not fail a refresh that previously ignored it.
157+
final pending = [
158+
for (final event in events)
159+
if (event.kind == 0 &&
160+
_isNewer(event.pubkey.toLowerCase(), event.createdAt, event.id))
161+
event,
162+
];
163+
if (pending.isEmpty) return true;
164+
final profiles = await ref.read(profileEventBatchParserProvider)(pending);
165+
if (!_isCurrent(generation)) return false;
166+
_mergeParsedProfiles(profiles);
167+
return true;
168+
});
169+
// Callers receive the original error; only the sequencing tail recovers so
170+
// one rejected batch does not poison all future refreshes.
171+
_verificationQueue = result.then<void>(
172+
(_) {},
173+
onError: (Object error, StackTrace stack) {},
174+
);
175+
return result;
176+
}
177+
178+
bool _isCurrent(int generation) => ref.mounted && generation == _generation;
179+
180+
void _mergeParsedProfiles(List<ParsedProfileEvent> profiles) {
181+
// Read the current state after the isolate completes: live events and other
182+
// batches may have installed newer profiles while this batch was parsing.
183+
final updated = Map<String, UserProfile>.from(state);
184+
var changed = false;
185+
for (final parsed in profiles) {
186+
if (!_isNewer(parsed.profile.pubkey, parsed.createdAt, parsed.eventId)) {
187+
continue;
188+
}
189+
updated[parsed.profile.pubkey] = parsed.profile;
190+
_profileEventOrders[parsed.profile.pubkey] = (
191+
createdAt: parsed.createdAt,
192+
eventId: parsed.eventId,
193+
);
194+
changed = true;
195+
}
196+
if (changed) state = updated;
197+
}
198+
199+
bool _isNewer(String pubkey, int createdAt, String eventId) {
200+
final current = _profileEventOrders[pubkey];
201+
return current == null ||
202+
createdAt > current.createdAt ||
203+
(createdAt == current.createdAt &&
204+
eventId.compareTo(current.eventId) < 0);
205+
}
206+
207+
bool _cacheProfileEvent(NostrEvent event, Map<String, UserProfile> profiles) {
159208
if (event.kind != 0) return false;
160-
final eventOrders = orders ?? _profileEventOrders;
161209
final pubkey = event.pubkey.toLowerCase();
162-
final current = eventOrders[pubkey];
163-
final isNewer =
164-
current == null ||
165-
event.createdAt > current.createdAt ||
166-
(event.createdAt == current.createdAt &&
167-
event.id.compareTo(current.eventId) < 0);
168-
if (!isNewer) return false;
169-
170-
profiles[pubkey] = _profileFromEvent(event);
171-
eventOrders[pubkey] = (createdAt: event.createdAt, eventId: event.id);
210+
if (!_isNewer(pubkey, event.createdAt, event.id)) return false;
211+
profiles[pubkey] = parseProfileEvent(event).profile;
212+
_profileEventOrders[pubkey] = (
213+
createdAt: event.createdAt,
214+
eventId: event.id,
215+
);
172216
return true;
173217
}
218+
}
174219

175-
UserProfile _profileFromEvent(NostrEvent event) {
176-
final data = ProfileData.fromEvent(event);
177-
final pubkey = data.pubkey.toLowerCase();
178-
return UserProfile(
179-
pubkey: pubkey,
180-
displayName: data.displayName,
181-
avatarUrl: data.avatarUrl,
182-
about: data.about,
183-
nip05Handle: data.nip05,
184-
ownerPubkey: verifiedOaOwnerPubkey(event.tags, event.pubkey),
220+
/// Profile history parser, isolated from provider state so batch completion can
221+
/// be delayed independently of relay delivery.
222+
final profileEventBatchParserProvider =
223+
Provider<Future<List<ParsedProfileEvent>> Function(List<NostrEvent>)>(
224+
(ref) => parseProfileEventBatch,
185225
);
186-
}
187-
}
188226

189227
final userCacheProvider =
190228
NotifierProvider<UserCacheNotifier, Map<String, UserProfile>>(

0 commit comments

Comments
 (0)