Skip to content

Commit 309e34d

Browse files
wpfleger96Hayt
andauthored
fix(mobile): converge sidebar managers on relay head with resume re-read (#7806)
Mobile half of the sidebar stale-reader fix (desktop: #7805). It makes the channel sections, sort, stars and mutes managers converge on the latest relay head. ## Changes - **Tie-break:** sections, stars and mutes compare `(created_at, id)` with `id < cursor`, which matches the relay's `ORDER BY created_at DESC, id ASC`. Sort already did this. - **Coherent cursor:** `_publish()` records the signed event ID through `SignedEventRelay.submit(onSigned:)` and advances `(_lastRemoteCreatedAt, _lastRemoteEventId)` together. It only advances when the pair is after the current cursor, so a newer head learned during the await is kept. This applies to sections, stars and mutes. - **Stars/mutes startup retry:** one serialized `_syncWithRelay()` (`_syncInFlight`/`_syncAgain`) with 2s→30s backoff. It retries until the history head is applied and the live subscription is settled. The stars/mutes managers no longer re-subscribe on CLOSED: `RelaySessionNotifier` owns retryable and rate-limited CLOSED, and a terminal CLOSED is never re-sent. Reconnect works through session replay and provider rebuild. Sections and sort keep their existing manager CLOSED retry. - **Stars/mutes durability:** storage `write()` returns the `setString()` result. A decode or apply error, or a persist that returns false or throws, fails the attempt. The accepted head only advances once it is durable, so the same head is retried. - **Stars/mutes pending fence:** each read snapshots `_localRevision` and `_publishPending`. If a local edit or a publish happened while the read was in flight, the result is discarded. Startup recovery retries it; a resume read does not. Per-entry arbitration is unchanged. - **Sections publish commits content with its cursor:** the submitted blob is committed together with its cursor, so a same-second loser applied during the OK wait can't strand the device. A local edit made during the wait is kept. - **Stars/mutes undecodable head:** an undecodable head is skipped without holding startup open. Only a persist failure keeps the head unapplied and retried. - **Resume re-read:** all four providers listen to `appLifecycleProvider`. On `resumed`, each manager runs one guarded history read through its existing fetch/apply path. It is one-shot: skipped when a local edit or publish is pending as it starts, not retried on failure, and it starts no timers or poll loop. The result is discarded if a mutation lands before it applies, and a disposed or superseded manager (sort generation fence) never persists it. ## Residuals - If the app stays in the foreground the whole time and a healthy socket drops an EVENT, the missed head is picked up on the next resume or reconnect. - Sections: a live event can still overwrite a pending local edit. This is pre-existing, and the resume read adds no new path to it. - Sort: a greater remote timestamp wins, by policy. - Stars/mutes: entries with equal `updatedAt` can still resolve differently on different clients, under the existing merge policy. - Stars/mutes: publish reads first and keeps the entry with the later `updatedAt`, so a peer whose clock runs fast can override a pending local entry. This rule already exists on main and matches desktop. - Sections and sort persistence failures are pre-existing and not redesigned here. ## Size Production: 10 files, +495/−162. Tests: 3 files, +718. The new `sidebar_sync_fixture.dart` runs over the real `RelaySessionNotifier` seam and is shared by `channel_reader_recovery_test.dart`. Plus a sections tie-break case. --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
1 parent 99c2acf commit 309e34d

13 files changed

Lines changed: 1213 additions & 162 deletions

‎mobile/lib/features/channels/channel_mutes/channel_mutes_manager.dart‎

Lines changed: 196 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ class ChannelMutesManager {
4545
void Function()? _unsubscribe;
4646
bool _disposed = false;
4747

48+
/// Base delay for the recovery-read retry backoff. Overridable in tests.
49+
final Duration _startupRetryBaseDelay;
50+
Timer? _startupRetryTimer;
51+
int _startupRetryAttempt = 0;
52+
bool _headApplied = false;
53+
bool _liveSettled = false;
54+
int _localRevision = 0;
55+
bool _publishPending = false;
56+
Future<void>? _syncInFlight;
57+
bool _syncAgain = false;
58+
4859
ChannelMutesManager({
4960
required this.pubkey,
5061
required SharedPreferences prefs,
@@ -53,12 +64,15 @@ class ChannelMutesManager {
5364
required SignedEventRelay? signedEventRelay,
5465
required bool remoteEnabled,
5566
required VoidCallback onChanged,
67+
@visibleForTesting
68+
Duration startupRetryBaseDelay = const Duration(seconds: 2),
5669
}) : _storage = ChannelMutesStorage(prefs),
5770
_crypto = crypto,
5871
_relaySession = relaySession,
5972
_signedEventRelay = signedEventRelay,
6073
_remoteEnabled = remoteEnabled,
6174
_onChanged = onChanged,
75+
_startupRetryBaseDelay = startupRetryBaseDelay,
6276
_store = ChannelMutesStorage(prefs).read(pubkey);
6377

6478
ChannelMuteStore get store => _store;
@@ -71,14 +85,84 @@ class ChannelMutesManager {
7185
return;
7286
}
7387

74-
await _fetchAndMerge();
75-
await _startLiveSubscription();
88+
await _syncWithRelay();
7689
_onChanged();
7790
}
7891

92+
/// Re-reads the retained head once, e.g. on app foreground resume, to catch
93+
/// an EVENT a healthy socket never delivered. One shot: skipped while an
94+
/// edit is pending, not retried on failure, and leaves startup state alone.
95+
void refreshFromRelay() {
96+
if (_disposed || !_remoteEnabled || _relaySession == null) return;
97+
unawaited(_recoverHead());
98+
}
99+
100+
/// Applies the retained head and opens the live subscription, retrying with
101+
/// bounded backoff (2s base, 30s ceiling) until both are done. Transient
102+
/// live-subscription CLOSED recovery belongs to [RelaySessionNotifier].
103+
Future<void> _syncWithRelay() {
104+
if (_disposed) return Future.value();
105+
final inFlight = _syncInFlight;
106+
if (inFlight != null) {
107+
_syncAgain = true;
108+
return inFlight;
109+
}
110+
final sync = _runSyncWithRelay();
111+
_syncInFlight = sync;
112+
return sync.whenComplete(() {
113+
_syncInFlight = null;
114+
if (_disposed || !_syncAgain) return;
115+
_syncAgain = false;
116+
unawaited(_syncWithRelay());
117+
});
118+
}
119+
120+
Future<void> _runSyncWithRelay() async {
121+
if (!_headApplied) {
122+
final applied = await _recoverHead();
123+
if (_disposed) return;
124+
_headApplied = applied;
125+
}
126+
127+
final subscribed = _liveSettled || await _startLiveSubscription();
128+
if (_disposed) return;
129+
130+
if (!_headApplied || !subscribed) {
131+
_scheduleStartupRetry();
132+
} else {
133+
_startupRetryAttempt = 0;
134+
}
135+
}
136+
137+
void _scheduleStartupRetry() {
138+
if (_disposed) return;
139+
_startupRetryTimer?.cancel();
140+
final delayMs = min(
141+
_startupRetryBaseDelay.inMilliseconds << min(_startupRetryAttempt, 5),
142+
30000,
143+
);
144+
_startupRetryAttempt++;
145+
debugPrint(
146+
'[ChannelMutesManager] relay sync incomplete; '
147+
'retrying in ${delayMs}ms (attempt $_startupRetryAttempt)',
148+
);
149+
_startupRetryTimer = Timer(Duration(milliseconds: delayMs), () {
150+
_startupRetryTimer = null;
151+
unawaited(
152+
_syncWithRelay().then((_) {
153+
if (!_disposed) _onChanged();
154+
}),
155+
);
156+
});
157+
}
158+
79159
void dispose({bool flushPending = true}) {
80160
if (_disposed) return;
81161
_disposed = true;
162+
_syncAgain = false;
163+
164+
_startupRetryTimer?.cancel();
165+
_startupRetryTimer = null;
82166

83167
final hadPending = _publishDebounce != null;
84168
_publishDebounce?.cancel();
@@ -99,7 +183,7 @@ class ChannelMutesManager {
99183
updatedAt: currentUnixSeconds(),
100184
);
101185
_store = ChannelMuteStore(channels: {..._store.channels, channelId: entry});
102-
_persist();
186+
unawaited(_persist());
103187
_onChanged();
104188
markDirty();
105189
}
@@ -111,101 +195,126 @@ class ChannelMutesManager {
111195
updatedAt: currentUnixSeconds(),
112196
);
113197
_store = ChannelMuteStore(channels: {..._store.channels, channelId: entry});
114-
_persist();
198+
unawaited(_persist());
115199
_onChanged();
116200
markDirty();
117201
}
118202

119203
void markDirty() {
120204
if (!_remoteEnabled || _disposed) return;
205+
_localRevision++;
206+
_publishPending = true;
121207
_publishDebounce?.cancel();
122208
_publishDebounce = Timer(const Duration(seconds: 5), () {
123209
_publishDebounce = null;
124-
unawaited(_publish());
210+
unawaited(
211+
_publish().whenComplete(
212+
() => _publishPending = _publishDebounce != null,
213+
),
214+
);
125215
});
126216
}
127217

128-
Future<void> _fetchAndMerge() async {
129-
if (_relaySession == null) return;
218+
/// A recovery read that loses to a local edit is deferred, never applied:
219+
/// a peer entry stamped by a skewed clock could otherwise overwrite it.
220+
Future<bool> _recoverHead() async {
221+
if (_publishPending) return false;
222+
final revision = _localRevision;
223+
final events = await _fetchHead();
224+
if (events == null || _disposed) return false;
225+
if (revision != _localRevision || _publishPending) return false;
226+
final applied = await _applyEvents(events);
227+
if (!_disposed) _onChanged();
228+
return applied;
229+
}
230+
231+
Future<List<NostrEvent>?> _fetchHead() async {
130232
try {
131-
final events = await _relaySession.fetchHistory(
132-
NostrFilter(
133-
kinds: const [EventKind.readState],
134-
authors: [pubkey],
135-
tags: const {
136-
'#d': ['channel-mutes'],
137-
},
138-
limit: 1,
139-
),
140-
);
141-
_mergeEvents(events);
142-
_persist();
143-
if (!_disposed) _onChanged();
144-
} catch (_) {
145-
// Local state remains usable when relay is unavailable.
233+
return await _relaySession!.fetchHistory(_filter());
234+
} catch (error) {
235+
debugPrint('[ChannelMutesManager] fetch failed: $error');
236+
return null;
146237
}
147238
}
148239

149-
Future<void> _startLiveSubscription() async {
150-
if (_relaySession == null) return;
240+
Future<bool> _startLiveSubscription() async {
151241
try {
152-
_unsubscribe = await _relaySession.subscribe(
153-
NostrFilter(
154-
kinds: const [EventKind.readState],
155-
authors: [pubkey],
156-
tags: const {
157-
'#d': ['channel-mutes'],
158-
},
159-
limit: 1,
160-
),
242+
final unsubscribe = await _relaySession!.subscribe(
243+
_filter(),
161244
_handleIncomingEvent,
245+
// Only terminal rejections reach here; re-sending the same REQ would
246+
// be rejected again, so the live lane stays settled.
247+
onClosed: (message) {
248+
_liveSettled = true;
249+
debugPrint(
250+
'[ChannelMutesManager] live subscription closed: $message',
251+
);
252+
},
162253
);
163-
} catch (_) {
164-
// Non-fatal — local state and history still work.
254+
if (_disposed) {
255+
unsubscribe();
256+
return false;
257+
}
258+
_unsubscribe = unsubscribe;
259+
return _liveSettled = true;
260+
} catch (error) {
261+
debugPrint('[ChannelMutesManager] live subscription failed: $error');
262+
return _liveSettled;
165263
}
166264
}
167265

168-
void _mergeEvents(List<NostrEvent> events) {
266+
NostrFilter _filter() => NostrFilter(
267+
kinds: const [EventKind.readState],
268+
authors: [pubkey],
269+
tags: const {
270+
'#d': ['channel-mutes'],
271+
},
272+
limit: 1,
273+
);
274+
275+
/// Relay retains `ORDER BY created_at DESC, id ASC`: at equal second the
276+
/// lower event ID wins.
277+
bool _isAfterCursor(int createdAt, String id) =>
278+
createdAt > _lastRemoteCreatedAt ||
279+
(createdAt == _lastRemoteCreatedAt &&
280+
id.compareTo(_lastRemoteEventId ?? '') < 0);
281+
282+
/// Returns false only when a newer head could not be persisted; the cursor
283+
/// then stays put so the same head is retried. An undecodable head is
284+
/// skipped without holding startup open.
285+
Future<bool> _applyEvents(List<NostrEvent> events) async {
286+
var applied = true;
169287
for (final event in events) {
170-
if (event.pubkey != pubkey) continue;
171-
_mergeEvent(event);
172-
}
173-
}
174-
175-
void _mergeEvent(NostrEvent event) {
176-
// Only process channel-mutes d-tag events.
177-
final dTag = event.getTagValue('d');
178-
if (dTag != 'channel-mutes') return;
179-
180-
try {
181-
final plaintext = _crypto.decrypt(event.content);
182-
final parsed = jsonDecode(plaintext);
183-
if (parsed is! Map<String, dynamic>) return;
184-
185-
final incoming = ChannelMuteStore.fromJson(parsed);
186-
187-
// Gate on createdAt: ignore events older than what we've already seen.
188-
final isNewer =
189-
event.createdAt > _lastRemoteCreatedAt ||
190-
(event.createdAt == _lastRemoteCreatedAt &&
191-
event.id.compareTo(_lastRemoteEventId ?? '') > 0);
192-
193-
if (isNewer) {
288+
if (event.pubkey != pubkey || event.getTagValue('d') != 'channel-mutes') {
289+
continue;
290+
}
291+
if (!_isAfterCursor(event.createdAt, event.id)) continue;
292+
try {
293+
final parsed = jsonDecode(_crypto.decrypt(event.content));
294+
if (parsed is! Map<String, dynamic>) throw const FormatException();
295+
// Per-channel merge: keep the entry with the highest updatedAt.
296+
_store = mergeStores(_store, ChannelMuteStore.fromJson(parsed));
297+
} catch (error) {
298+
debugPrint('[ChannelMutesManager] undecodable head: $error');
299+
continue;
300+
}
301+
if (!await _persist()) {
302+
applied = false;
303+
continue;
304+
}
305+
if (_isAfterCursor(event.createdAt, event.id)) {
194306
_lastRemoteCreatedAt = event.createdAt;
195307
_lastRemoteEventId = event.id;
196-
// Per-channel merge: keep the entry with the highest updatedAt for each channel.
197-
_store = mergeStores(_store, incoming);
198-
_persist();
199308
}
200-
} catch (_) {
201-
// Decryption failure or parse error — keep existing state.
202309
}
310+
return applied;
203311
}
204312

205313
void _handleIncomingEvent(NostrEvent event) {
206314
if (_disposed) return;
207-
_mergeEvent(event);
208-
if (!_disposed) _onChanged();
315+
unawaited(
316+
_applyEvents([event]).then((_) => _disposed ? null : _onChanged()),
317+
);
209318
}
210319

211320
bool _isIdenticalToLastPublished() {
@@ -232,7 +341,9 @@ class ChannelMutesManager {
232341
}
233342

234343
// Read-before-write: merge remote state before publishing
235-
await _fetchAndMerge();
344+
final events = await _fetchHead();
345+
if (events != null) await _applyEvents(events);
346+
if (!_disposed) _onChanged();
236347

237348
// No-op suppression: skip if nothing changed
238349
if (_isIdenticalToLastPublished()) return;
@@ -242,6 +353,7 @@ class ChannelMutesManager {
242353
final ciphertext = _crypto.encrypt(payload);
243354
final createdAt = max(currentUnixSeconds(), _lastRemoteCreatedAt + 1);
244355

356+
String? signedId;
245357
await _signedEventRelay.submit(
246358
kind: EventKind.readState,
247359
content: ciphertext,
@@ -250,16 +362,29 @@ class ChannelMutesManager {
250362
['t', 'channel-mutes'],
251363
],
252364
createdAt: createdAt,
365+
onSigned: (event) => signedId = event.id,
253366
);
254367

255-
_lastRemoteCreatedAt = max(_lastRemoteCreatedAt, createdAt);
368+
// Keep the cursor a coherent (created_at, id) pair so an OK that beats
369+
// its own echo cannot make later same-second heads compare against a
370+
// stale ID. A newer head learned during the await stays.
371+
if (signedId != null && _isAfterCursor(createdAt, signedId!)) {
372+
_lastRemoteCreatedAt = createdAt;
373+
_lastRemoteEventId = signedId;
374+
}
256375
_lastPublishedStore = ChannelMuteStore(channels: Map.of(_store.channels));
257376
} catch (error) {
258377
debugPrint('[ChannelMutesManager] publish failed: $error');
259378
}
260379
}
261380

262-
void _persist() {
263-
_storage.write(pubkey, _store);
381+
Future<bool> _persist() async {
382+
try {
383+
if (await _storage.write(pubkey, _store)) return true;
384+
debugPrint('[ChannelMutesManager] persist returned false');
385+
} catch (error) {
386+
debugPrint('[ChannelMutesManager] persist failed: $error');
387+
}
388+
return false;
264389
}
265390
}

‎mobile/lib/features/channels/channel_mutes/channel_mutes_provider.dart‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import 'package:flutter/widgets.dart';
12
import 'package:hooks_riverpod/hooks_riverpod.dart';
23
import 'package:nostr/nostr.dart' as nostr;
34

@@ -69,6 +70,11 @@ class ChannelMutesNotifier extends Notifier<ChannelMutesState> {
6970
);
7071
_manager = manager;
7172

73+
// Resume re-read catches an EVENT a healthy socket never delivered.
74+
ref.listen(appLifecycleProvider, (_, next) {
75+
if (next == AppLifecycleState.resumed) manager.refreshFromRelay();
76+
});
77+
7278
ref.onDispose(() {
7379
manager.dispose();
7480
if (_manager == manager) {

‎mobile/lib/features/channels/channel_mutes/channel_mutes_storage.dart‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,6 @@ class ChannelMutesStorage {
8585
}
8686
}
8787

88-
void write(String pubkey, ChannelMuteStore store) {
89-
_prefs.setString(channelMutesKey(pubkey), jsonEncode(store.toJson()));
90-
}
88+
Future<bool> write(String pubkey, ChannelMuteStore store) =>
89+
_prefs.setString(channelMutesKey(pubkey), jsonEncode(store.toJson()));
9190
}

0 commit comments

Comments
 (0)