Skip to content

Commit c5f1d9a

Browse files
author
npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w
committed
fix(mobile): retry channel-sections startup sync when relay rate-limits cold start
On mobile cold start, ChannelsNotifier fires a burst of per-channel REQs that exhausts the relay's per-connection rate-limit quota. The sections manager then has BOTH its one-shot history fetch and its live subscription rejected with 'rate-limited: quota exceeded'. Both errors were silently swallowed with no retry, so the manager kept the local (empty/default) store forever and desktop-created channel groups never appeared on mobile. Restarts replay the same storm, so the failure is sticky. Fix: track whether the startup fetch and the live subscription have succeeded, and retry _syncWithRelay with exponential backoff (2s base, capped at 30s) until both land. The retry timer is cancelled on dispose and previously swallowed errors are now logged. Verified live on the Android emulator: cold-start logs show the manager rate-limited, then a 2s retry succeeding and desktop-created groups rendering. Regression tests cover retry-until-adopted, retry stopping after success, and dispose cancelling pending retries. Co-authored-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz> Signed-off-by: npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6w <52a228d6edf316ec6812ac3c9fc0d696ab59fc7954d77e7be31eedcddf91335b@buzz.block.builderlab.xyz>
1 parent 74b63e1 commit c5f1d9a

2 files changed

Lines changed: 276 additions & 9 deletions

File tree

‎mobile/lib/features/channels/channel_sections/channel_sections_manager.dart‎

Lines changed: 70 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ class ChannelSectionsManager {
4848
void Function()? _unsubscribe;
4949
bool _disposed = false;
5050

51+
/// Base delay for the startup-sync retry backoff. Overridable in tests.
52+
final Duration _startupRetryBaseDelay;
53+
Timer? _startupRetryTimer;
54+
int _startupRetryAttempt = 0;
55+
bool _startupFetchSucceeded = false;
56+
5157
ChannelSectionsManager({
5258
required this.pubkey,
5359
required SharedPreferences prefs,
@@ -56,12 +62,15 @@ class ChannelSectionsManager {
5662
required SignedEventRelay? signedEventRelay,
5763
required bool remoteEnabled,
5864
required VoidCallback onChanged,
65+
@visibleForTesting
66+
Duration startupRetryBaseDelay = const Duration(seconds: 2),
5967
}) : _storage = ChannelSectionsStorage(prefs),
6068
_crypto = crypto,
6169
_relaySession = relaySession,
6270
_signedEventRelay = signedEventRelay,
6371
_remoteEnabled = remoteEnabled,
6472
_onChanged = onChanged,
73+
_startupRetryBaseDelay = startupRetryBaseDelay,
6574
_store = ChannelSectionsStorage(prefs).read(pubkey);
6675

6776
ChannelSectionStore get store => _store;
@@ -74,15 +83,57 @@ class ChannelSectionsManager {
7483
return;
7584
}
7685

77-
await _fetchAndMerge();
78-
await _startLiveSubscription();
86+
await _syncWithRelay();
7987
_onChanged();
8088
}
8189

90+
/// One startup-sync attempt: fetch the remote blob, then start the live
91+
/// subscription. Either step can lose a transient race on cold start (the
92+
/// relay rate-limits the burst of per-channel subscriptions and rejects
93+
/// with `rate-limited: quota exceeded`) — retry with backoff instead of
94+
/// silently giving up, which left desktop-created groups invisible until
95+
/// an unrelated refetch.
96+
Future<void> _syncWithRelay() async {
97+
if (!_startupFetchSucceeded) {
98+
_startupFetchSucceeded = await _fetchAndMerge();
99+
}
100+
101+
final subscribed = _unsubscribe != null || await _startLiveSubscription();
102+
103+
if (!_startupFetchSucceeded || !subscribed) {
104+
_scheduleStartupRetry();
105+
}
106+
}
107+
108+
void _scheduleStartupRetry() {
109+
if (_disposed) return;
110+
_startupRetryTimer?.cancel();
111+
final delayMs = min(
112+
_startupRetryBaseDelay.inMilliseconds << min(_startupRetryAttempt, 5),
113+
30000,
114+
);
115+
_startupRetryAttempt++;
116+
debugPrint(
117+
'[ChannelSectionsManager] startup sync incomplete; '
118+
'retrying in ${delayMs}ms (attempt $_startupRetryAttempt)',
119+
);
120+
_startupRetryTimer = Timer(Duration(milliseconds: delayMs), () {
121+
_startupRetryTimer = null;
122+
unawaited(
123+
_syncWithRelay().then((_) {
124+
if (!_disposed) _onChanged();
125+
}),
126+
);
127+
});
128+
}
129+
82130
void dispose({bool flushPending = true}) {
83131
if (_disposed) return;
84132
_disposed = true;
85133

134+
_startupRetryTimer?.cancel();
135+
_startupRetryTimer = null;
136+
86137
final hadPending = _publishDebounce != null;
87138
_publishDebounce?.cancel();
88139
_publishDebounce = null;
@@ -201,8 +252,10 @@ class ChannelSectionsManager {
201252
});
202253
}
203254

204-
Future<void> _fetchAndMerge() async {
205-
if (_relaySession == null) return;
255+
/// Returns whether the fetch reached the relay (regardless of whether a
256+
/// remote blob exists).
257+
Future<bool> _fetchAndMerge() async {
258+
if (_relaySession == null) return false;
206259
try {
207260
final events = await _relaySession.fetchHistory(
208261
NostrFilter(
@@ -217,13 +270,17 @@ class ChannelSectionsManager {
217270
_mergeEvents(events);
218271
_persist();
219272
if (!_disposed) _onChanged();
220-
} catch (_) {
273+
return true;
274+
} catch (error) {
275+
debugPrint('[ChannelSectionsManager] fetch failed: $error');
221276
// Local state remains usable when relay is unavailable.
277+
return false;
222278
}
223279
}
224280

225-
Future<void> _startLiveSubscription() async {
226-
if (_relaySession == null) return;
281+
/// Returns whether the live subscription was established.
282+
Future<bool> _startLiveSubscription() async {
283+
if (_relaySession == null) return false;
227284
try {
228285
_unsubscribe = await _relaySession.subscribe(
229286
NostrFilter(
@@ -236,8 +293,12 @@ class ChannelSectionsManager {
236293
),
237294
_handleIncomingEvent,
238295
);
239-
} catch (_) {
240-
// Non-fatal — local state and history still work.
296+
return true;
297+
} catch (error) {
298+
debugPrint('[ChannelSectionsManager] live subscription failed: $error');
299+
// Non-fatal — local state and history still work; retried by the
300+
// startup-sync backoff.
301+
return false;
241302
}
242303
}
243304

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
import 'dart:convert';
2+
3+
import 'package:flutter_test/flutter_test.dart';
4+
import 'package:nostr/nostr.dart' as nostr;
5+
import 'package:shared_preferences/shared_preferences.dart';
6+
import 'package:buzz/features/channels/channel_sections/channel_sections_manager.dart';
7+
import 'package:buzz/shared/relay/relay.dart';
8+
9+
void main() {
10+
late SharedPreferences prefs;
11+
late nostr.Keys keychain;
12+
late ChannelSectionsCrypto crypto;
13+
14+
Future<void> setUpEnv() async {
15+
SharedPreferences.setMockInitialValues({});
16+
prefs = await SharedPreferences.getInstance();
17+
keychain = nostr.Keys.generate();
18+
crypto = ChannelSectionsCrypto(keychain.nsec, keychain.public);
19+
}
20+
21+
NostrEvent sectionsEvent({
22+
required List<Map<String, dynamic>> sections,
23+
Map<String, String> assignments = const {},
24+
required int createdAt,
25+
String id = 'remote-event',
26+
}) {
27+
final payload = jsonEncode({
28+
'version': 1,
29+
'sections': sections,
30+
'assignments': assignments,
31+
});
32+
return NostrEvent(
33+
id: id,
34+
pubkey: keychain.public,
35+
createdAt: createdAt,
36+
kind: EventKind.readState,
37+
tags: const [
38+
['d', 'channel-sections'],
39+
['t', 'channel-sections'],
40+
],
41+
content: crypto.encrypt(payload),
42+
sig: 'sig',
43+
);
44+
}
45+
46+
ChannelSectionsManager buildManager({
47+
required RelaySessionNotifier relaySession,
48+
Duration startupRetryBaseDelay = const Duration(milliseconds: 5),
49+
}) {
50+
return ChannelSectionsManager(
51+
pubkey: keychain.public,
52+
prefs: prefs,
53+
crypto: crypto,
54+
relaySession: relaySession,
55+
signedEventRelay: null,
56+
remoteEnabled: true,
57+
onChanged: () {},
58+
startupRetryBaseDelay: startupRetryBaseDelay,
59+
);
60+
}
61+
62+
test('startup fetch rejected by relay rate limit retries until the remote '
63+
'blob is adopted (cold-start regression)', () async {
64+
await setUpEnv();
65+
// Cold start: the relay rejects the first fetch AND the first live
66+
// subscription with `rate-limited: quota exceeded` because the channel
67+
// list fired dozens of REQs first. Pre-fix, both errors were swallowed
68+
// and desktop-created groups never appeared until app data was cleared.
69+
final relay = _RateLimitedRelaySession(
70+
failuresBeforeSuccess: 2,
71+
historyEvents: [
72+
sectionsEvent(
73+
sections: [
74+
{'id': 's1', 'name': 'Desktop Group', 'order': 0},
75+
],
76+
createdAt: 100,
77+
),
78+
],
79+
);
80+
81+
final manager = buildManager(
82+
relaySession: relay,
83+
startupRetryBaseDelay: const Duration(milliseconds: 10),
84+
);
85+
await manager.initialize();
86+
87+
expect(
88+
manager.store.sections,
89+
isEmpty,
90+
reason: 'first fetch lost the rate-limit race',
91+
);
92+
93+
// Wait for the backoff retries (10ms, 20ms, …) to win the race.
94+
await _waitUntil(() => manager.store.sections.isNotEmpty);
95+
96+
expect(manager.store.sections.single.name, 'Desktop Group');
97+
expect(
98+
relay.subscribeCalls,
99+
greaterThan(1),
100+
reason: 'live subscription must be retried too',
101+
);
102+
manager.dispose(flushPending: false);
103+
});
104+
105+
test(
106+
'startup retry stops after fetch and subscription both succeed',
107+
() async {
108+
await setUpEnv();
109+
final relay = _RateLimitedRelaySession(
110+
failuresBeforeSuccess: 1,
111+
historyEvents: [
112+
sectionsEvent(
113+
sections: [
114+
{'id': 's1', 'name': 'Desktop Group', 'order': 0},
115+
],
116+
createdAt: 100,
117+
),
118+
],
119+
);
120+
final manager = buildManager(relaySession: relay);
121+
await manager.initialize();
122+
await _waitUntil(() => manager.store.sections.isNotEmpty);
123+
124+
final fetchCallsAfterSuccess = relay.fetchCalls;
125+
final subscribeCallsAfterSuccess = relay.subscribeCalls;
126+
await Future<void>.delayed(const Duration(milliseconds: 60));
127+
128+
expect(relay.fetchCalls, fetchCallsAfterSuccess);
129+
expect(relay.subscribeCalls, subscribeCallsAfterSuccess);
130+
manager.dispose(flushPending: false);
131+
},
132+
);
133+
134+
test('disposing the manager cancels pending startup retries', () async {
135+
await setUpEnv();
136+
final relay = _RateLimitedRelaySession(failuresBeforeSuccess: 1000);
137+
final manager = buildManager(relaySession: relay);
138+
await manager.initialize();
139+
manager.dispose(flushPending: false);
140+
141+
final fetchCallsAtDispose = relay.fetchCalls;
142+
await Future<void>.delayed(const Duration(milliseconds: 60));
143+
144+
expect(
145+
relay.fetchCalls,
146+
fetchCallsAtDispose,
147+
reason: 'no retries may fire after dispose',
148+
);
149+
});
150+
}
151+
152+
Future<void> _waitUntil(
153+
bool Function() condition, {
154+
Duration timeout = const Duration(seconds: 2),
155+
}) async {
156+
final deadline = DateTime.now().add(timeout);
157+
while (!condition()) {
158+
if (DateTime.now().isAfter(deadline)) {
159+
fail('condition not met within $timeout');
160+
}
161+
await Future<void>.delayed(const Duration(milliseconds: 10));
162+
}
163+
}
164+
165+
/// Rejects the first [failuresBeforeSuccess] fetch and subscribe calls with
166+
/// the relay's rate-limit error, then succeeds — the exact failure mode seen
167+
/// on Android cold start where the channel-list REQ burst exhausts the
168+
/// relay's per-connection quota before the sections manager gets a turn.
169+
class _RateLimitedRelaySession extends RelaySessionNotifier {
170+
_RateLimitedRelaySession({
171+
required this.failuresBeforeSuccess,
172+
this.historyEvents = const [],
173+
});
174+
175+
final int failuresBeforeSuccess;
176+
final List<NostrEvent> historyEvents;
177+
int fetchCalls = 0;
178+
int subscribeCalls = 0;
179+
final List<void Function(NostrEvent)> _listeners = [];
180+
181+
@override
182+
Future<List<NostrEvent>> fetchHistory(
183+
NostrFilter filter, {
184+
Duration timeout = const Duration(seconds: 8),
185+
}) async {
186+
fetchCalls++;
187+
if (fetchCalls <= failuresBeforeSuccess) {
188+
throw Exception('rate-limited: quota exceeded; retry in 2s');
189+
}
190+
return historyEvents;
191+
}
192+
193+
@override
194+
Future<void Function()> subscribe(
195+
NostrFilter filter,
196+
void Function(NostrEvent) onEvent, {
197+
void Function(String message)? onClosed,
198+
}) async {
199+
subscribeCalls++;
200+
if (subscribeCalls <= failuresBeforeSuccess) {
201+
throw Exception('rate-limited: quota exceeded; retry in 1s');
202+
}
203+
_listeners.add(onEvent);
204+
return () => _listeners.remove(onEvent);
205+
}
206+
}

0 commit comments

Comments
 (0)