@@ -3,10 +3,10 @@ import 'dart:async';
33import 'package:hooks_riverpod/hooks_riverpod.dart' ;
44
55import '../community/community_provider.dart' ;
6- import '../crypto/nip_oa.dart' ;
76import '../push/push_presentation_cache.dart' ;
87import '../relay/relay.dart' ;
98import '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';
1515class 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
189227final userCacheProvider =
190228 NotifierProvider <UserCacheNotifier , Map <String , UserProfile >>(
0 commit comments