Skip to content

Commit 37b7b6c

Browse files
browclaude
andcommitted
fix(mobile): serialize read-state re-syncs and skip the cold-start one
Overlapping reconnects could each install a live subscription and leak one, so re-syncs now run one at a time and reconnects waiting on a pass share it. A connect that lands while the first initialize is running no longer syncs again when that initialize succeeded. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent f94867b commit 37b7b6c

2 files changed

Lines changed: 156 additions & 13 deletions

File tree

‎mobile/lib/shared/read_state/read_state_manager.dart‎

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ class ReadStateManager {
6767
// Pending first fetch and subscribe. A reconnect while it runs waits for it
6868
// so two passes cannot each install a live subscription and leak one.
6969
Future<void>? _initializing;
70+
// The reconnect pass running now, and the one waiting to start after it.
71+
Future<void>? _runningResync;
72+
Future<void>? _queuedResync;
73+
// Whether the first fetch and subscribe both succeeded. A connect that
74+
// lands while they run (the cold-start connect) then has nothing to redo.
75+
bool _initialSyncSucceeded = false;
7076
bool _disposed = false;
7177
bool _isPublishing = false;
7278
// Set when a publish is asked for while one is running. The running
@@ -117,9 +123,11 @@ class ReadStateManager {
117123
final initializing = Completer<void>();
118124
_initializing = initializing.future;
119125
try {
120-
await _fetchAndMerge();
121-
await _startLiveSubscription();
126+
final fetched = await _fetchAndMerge();
127+
final subscribed = await _startLiveSubscription();
128+
_initialSyncSucceeded = fetched && subscribed;
122129
} finally {
130+
_initializing = null;
123131
initializing.complete();
124132
}
125133
if (!_isIdenticalToLastPublished(_currentContexts())) {
@@ -171,11 +179,44 @@ class ReadStateManager {
171179
await _publish();
172180
}
173181

174-
Future<void> reinitializeRemote() async {
175-
if (_disposed || !_remoteEnabled || !_initialized) return;
182+
/// Fetch and resubscribe after a reconnect. Passes run one at a time, so
183+
/// each replaces the previous live subscription instead of leaking one.
184+
/// Reconnects while a pass waits to start share that pass.
185+
Future<void> reinitializeRemote() {
186+
if (_disposed || !_remoteEnabled || !_initialized) return Future.value();
187+
final queued = _queuedResync;
188+
if (queued != null) return queued;
189+
final running = _runningResync;
190+
final initializing = _initializing;
191+
final pass = Completer<void>();
192+
_queuedResync = pass.future;
193+
unawaited(() async {
194+
try {
195+
if (running != null) {
196+
await running;
197+
} else if (initializing != null) {
198+
await initializing;
199+
// Connected while the first sync ran: it already used this
200+
// connection.
201+
if (_initialSyncSucceeded) return;
202+
}
203+
if (_disposed) return;
204+
if (identical(_queuedResync, pass.future)) _queuedResync = null;
205+
_runningResync = pass.future;
206+
await _resyncRemote();
207+
} catch (e) {
208+
debugPrint('[ReadStateManager] reinitializeRemote failed: $e');
209+
} finally {
210+
if (identical(_queuedResync, pass.future)) _queuedResync = null;
211+
if (identical(_runningResync, pass.future)) _runningResync = null;
212+
pass.complete();
213+
}
214+
}());
215+
return pass.future;
216+
}
217+
218+
Future<void> _resyncRemote() async {
176219
debugPrint('[ReadStateManager] reinitializeRemote');
177-
await _initializing;
178-
if (_disposed) return;
179220
if (_isPublishing) {
180221
await _publishCompleter?.future;
181222
}
@@ -232,7 +273,7 @@ class ReadStateManager {
232273
return true;
233274
}
234275

235-
Future<void> _fetchAndMerge() async {
276+
Future<bool> _fetchAndMerge() async {
236277
try {
237278
final events = await _relaySession!.fetchHistory(
238279
NostrFilter(
@@ -248,8 +289,10 @@ class ReadStateManager {
248289
_mergeEvents(events);
249290
_persistLocalState();
250291
_onChanged();
292+
return true;
251293
} catch (e) {
252294
debugPrint('[ReadStateManager] fetchAndMerge failed: $e');
295+
return false;
253296
}
254297
}
255298

@@ -321,7 +364,7 @@ class ReadStateManager {
321364
return changed;
322365
}
323366

324-
Future<void> _startLiveSubscription() async {
367+
Future<bool> _startLiveSubscription() async {
325368
try {
326369
final unsub = await _relaySession!.subscribe(
327370
NostrFilter(
@@ -336,12 +379,14 @@ class ReadStateManager {
336379
);
337380
if (_disposed) {
338381
unsub.call();
339-
return;
382+
return false;
340383
}
341384
_unsubscribeLive = unsub;
342385
debugPrint('[ReadStateManager] live subscription established');
386+
return true;
343387
} catch (e) {
344388
debugPrint('[ReadStateManager] live subscription FAILED: $e');
389+
return false;
345390
}
346391
}
347392

‎mobile/test/features/channels/read_state/read_state_manager_test.dart‎

Lines changed: 102 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -557,18 +557,64 @@ void main() {
557557
expect(manager.getEffectiveTimestamp('channel-1'), 300);
558558
});
559559

560-
test('a reconnect during initialize leaves one live subscription', () async {
560+
test(
561+
'a connect during a successful initialize does not sync again',
562+
() async {
563+
SharedPreferences.setMockInitialValues({});
564+
final prefs = await SharedPreferences.getInstance();
565+
final keychain = nostr.Keys.generate();
566+
final crypto = ReadStateCrypto.tryCreate(
567+
nsec: keychain.nsec,
568+
pubkey: keychain.public,
569+
)!;
570+
// First connect: initialize waits on a history REQ held for the socket
571+
// while the session reports connected and the provider's listener fires.
572+
final gate = Completer<void>();
573+
final relay = _FakeRelaySession()..fetchGate = gate.future;
574+
final manager = ReadStateManager(
575+
pubkey: keychain.public,
576+
relayUrl: _relayUrl,
577+
prefs: prefs,
578+
crypto: crypto,
579+
relaySession: relay,
580+
signedEventRelay: _FakeSignedEventRelay(),
581+
remoteEnabled: true,
582+
onChanged: () {},
583+
);
584+
585+
final initializing = manager.initialize();
586+
final reinitializing = manager.reinitializeRemote();
587+
relay.fetchGate = null;
588+
gate.complete();
589+
await Future.wait([initializing, reinitializing]);
590+
591+
expect(relay.fetchCount, 1);
592+
expect(relay.subscribeCount, 1);
593+
expect(relay.liveSubscriptions, 1);
594+
595+
// A later reconnect syncs again and still leaves one subscription.
596+
await manager.reinitializeRemote();
597+
expect(relay.fetchCount, 2);
598+
expect(relay.subscribeCount, 2);
599+
expect(relay.liveSubscriptions, 1);
600+
601+
manager.dispose();
602+
expect(relay.liveSubscriptions, 0);
603+
},
604+
);
605+
606+
test('a connect during a failed initialize syncs again', () async {
561607
SharedPreferences.setMockInitialValues({});
562608
final prefs = await SharedPreferences.getInstance();
563609
final keychain = nostr.Keys.generate();
564610
final crypto = ReadStateCrypto.tryCreate(
565611
nsec: keychain.nsec,
566612
pubkey: keychain.public,
567613
)!;
568-
// First connect: initialize waits on a history REQ held for the socket
569-
// while the session reports connected and the provider's listener fires.
570614
final gate = Completer<void>();
571-
final relay = _FakeRelaySession()..fetchGate = gate.future;
615+
final relay = _FakeRelaySession()
616+
..fetchGate = gate.future
617+
..failNextFetch = true;
572618
final manager = ReadStateManager(
573619
pubkey: keychain.public,
574620
relayUrl: _relayUrl,
@@ -587,13 +633,58 @@ void main() {
587633
await Future.wait([initializing, reinitializing]);
588634

589635
// Both passes subscribed, but the later one replaced the earlier one.
636+
expect(relay.fetchCount, 2);
590637
expect(relay.subscribeCount, 2);
591638
expect(relay.liveSubscriptions, 1);
592639

593640
manager.dispose();
594641
expect(relay.liveSubscriptions, 0);
595642
});
596643

644+
test('reconnects during a re-sync leave one live subscription', () async {
645+
SharedPreferences.setMockInitialValues({});
646+
final prefs = await SharedPreferences.getInstance();
647+
final keychain = nostr.Keys.generate();
648+
final crypto = ReadStateCrypto.tryCreate(
649+
nsec: keychain.nsec,
650+
pubkey: keychain.public,
651+
)!;
652+
final relay = _FakeRelaySession();
653+
final manager = ReadStateManager(
654+
pubkey: keychain.public,
655+
relayUrl: _relayUrl,
656+
prefs: prefs,
657+
crypto: crypto,
658+
relaySession: relay,
659+
signedEventRelay: _FakeSignedEventRelay(),
660+
remoteEnabled: true,
661+
onChanged: () {},
662+
);
663+
await manager.initialize();
664+
665+
// The first re-sync holds its fetch; three more connects arrive.
666+
final gate = Completer<void>();
667+
relay.fetchGate = gate.future;
668+
final first = manager.reinitializeRemote();
669+
await Future<void>.delayed(Duration.zero);
670+
final later = [
671+
manager.reinitializeRemote(),
672+
manager.reinitializeRemote(),
673+
manager.reinitializeRemote(),
674+
];
675+
relay.fetchGate = null;
676+
gate.complete();
677+
await Future.wait([first, ...later]);
678+
679+
// One initial pass, the held re-sync, and one shared re-sync after it.
680+
expect(relay.fetchCount, 3);
681+
expect(relay.subscribeCount, 3);
682+
expect(relay.liveSubscriptions, 1);
683+
684+
manager.dispose();
685+
expect(relay.liveSubscriptions, 0);
686+
});
687+
597688
test('remote read-state rollback is ignored', () async {
598689
SharedPreferences.setMockInitialValues({});
599690
final prefs = await SharedPreferences.getInstance();
@@ -779,6 +870,8 @@ NostrEvent _readStateEvent({
779870
class _FakeRelaySession extends RelaySessionNotifier {
780871
List<NostrEvent> historyEvents = [];
781872
Future<void>? fetchGate;
873+
bool failNextFetch = false;
874+
int fetchCount = 0;
782875
int subscribeCount = 0;
783876
int liveSubscriptions = 0;
784877

@@ -787,7 +880,12 @@ class _FakeRelaySession extends RelaySessionNotifier {
787880
NostrFilter filter, {
788881
Duration timeout = const Duration(seconds: 8),
789882
}) async {
883+
fetchCount++;
790884
await fetchGate;
885+
if (failNextFetch) {
886+
failNextFetch = false;
887+
throw TimeoutException('history timed out');
888+
}
791889
return historyEvents;
792890
}
793891

0 commit comments

Comments
 (0)