Skip to content

Commit 15c65c7

Browse files
browsquare-tombcoreystudioperfie
authored
fix(mobile): keep a superseded roster read out of the offline snapshot (#9452)
The channel member list keeps a snapshot of the last roster it read, which it shows while the relay is disconnected. When two roster updates arrive close together, the member list starts a read for each. If the first read answered after the second, it still wrote its older roster over the snapshot. The live list stayed correct, but once the app went offline it showed the older roster: for example, a member just removed, or a bot role just changed, came back. A read that a later read has replaced no longer writes the snapshot. The snapshot cache numbers each read of a channel's roster, and only the latest read for that channel may write. A read that ends because nothing is watching the list any more (the user leaves the screen mid-read, or a one-off lookup such as sending a message) still writes, since its roster is the newest one. ### Validation New tests, which fail without this change: - Two roster updates arrive, the second read answers first and the first answers after it, with a roster, with no roster event, or with an empty roster. Once disconnected, the member list still shows the newer roster. - A roster update arrives and the user leaves before its read answers. Once disconnected, the member list shows that newer roster. (This passes on main and guards against fencing on disposal, which an earlier version of this PR did.) The rest of the channel management tests pass unchanged. Full mobile test suite and `flutter analyze` pass. The race itself needs two roster reads to answer out of order and then a disconnect, which a device run can't reliably produce. An automated run on an iPhone 12 mini signed in to Block's Builderlab (profile build of this head) covered the roster paths it touches: cold start, searching for and opening buzz-mobile, its details (86 members) and its member list (49 people, roles shown), scrolling it, backgrounding the app for 60 seconds, resuming, and reopening the member list, which loaded the same roster. ### Regressions None. A replaced read's result was already discarded for the live list; now it is also kept out of the offline snapshot. Reads that nothing replaced write the snapshot as before. --------- Signed-off-by: Tom Brow <[email protected]> Co-authored-by: Tom Brow <[email protected]> Co-authored-by: corey <2dafccf60ea6d431a568f6d67fc60016c1b2a51e415e09dc8b213b8e3606cf54@buzz.block.builderlab.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: perfie <1fc92b08616bef6025a30fa24528ba2417d2a0c82f2c67b62e7f912089235028@buzz.block.builderlab.xyz>
1 parent 99e65b6 commit 15c65c7

2 files changed

Lines changed: 178 additions & 3 deletions

File tree

‎mobile/lib/features/channels/channel_management_provider.dart‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ String _channelMemberSnapshotKey({
114114

115115
class _ChannelMembersSnapshotCache {
116116
final _membersByKey = <String, List<ChannelMember>>{};
117+
final _latestReadByKey = <String, int>{};
117118

118119
List<ChannelMember>? read({
119120
required String relayBaseUrl,
@@ -126,19 +127,35 @@ class _ChannelMembersSnapshotCache {
126127
channelId: channelId,
127128
)];
128129

130+
/// Starts a roster read for this scope and returns its generation. A later
131+
/// call supersedes it, so its [write] is then ignored.
132+
int beginRead({
133+
required String relayBaseUrl,
134+
required String? pubkey,
135+
required String channelId,
136+
}) {
137+
final key = _channelMemberSnapshotKey(
138+
relayBaseUrl: relayBaseUrl,
139+
pubkey: pubkey,
140+
channelId: channelId,
141+
);
142+
return _latestReadByKey[key] = (_latestReadByKey[key] ?? 0) + 1;
143+
}
144+
129145
void write({
130146
required String relayBaseUrl,
131147
required String? pubkey,
132148
required String channelId,
149+
required int generation,
133150
required List<ChannelMember> members,
134151
}) {
135-
_membersByKey[_channelMemberSnapshotKey(
152+
final key = _channelMemberSnapshotKey(
136153
relayBaseUrl: relayBaseUrl,
137154
pubkey: pubkey,
138155
channelId: channelId,
139-
)] = List.unmodifiable(
140-
members,
141156
);
157+
if (_latestReadByKey[key] != generation) return;
158+
_membersByKey[key] = List.unmodifiable(members);
142159
}
143160
}
144161

@@ -384,6 +401,14 @@ final channelMembersProvider = FutureProvider.autoDispose
384401
final relayBaseUrl = ref.watch(relayConfigProvider).baseUrl;
385402
final pubkey = ref.watch(myPubkeyProvider)?.toLowerCase();
386403
final snapshotCache = ref.read(_channelMembersSnapshotCacheProvider);
404+
// A read superseded by a later one (a roster update arriving mid-read)
405+
// must not overwrite the snapshot the newer read already wrote. A read
406+
// torn down with nothing newer still writes: it has the latest roster.
407+
final generation = snapshotCache.beginRead(
408+
relayBaseUrl: relayBaseUrl,
409+
pubkey: pubkey,
410+
channelId: channelId,
411+
);
387412
// Re-fetch only after reconnect completes. During the disconnected
388413
// interval this provider has no session dependency, so its current value
389414
// remains visible to every consumer rather than becoming AsyncData([]).
@@ -409,6 +434,7 @@ final channelMembersProvider = FutureProvider.autoDispose
409434
relayBaseUrl: relayBaseUrl,
410435
pubkey: pubkey,
411436
channelId: channelId,
437+
generation: generation,
412438
members: channelListMembers,
413439
);
414440
return channelListMembers;
@@ -424,6 +450,7 @@ final channelMembersProvider = FutureProvider.autoDispose
424450
relayBaseUrl: relayBaseUrl,
425451
pubkey: pubkey,
426452
channelId: channelId,
453+
generation: generation,
427454
members: const [],
428455
);
429456
return const [];
@@ -446,6 +473,7 @@ final channelMembersProvider = FutureProvider.autoDispose
446473
relayBaseUrl: relayBaseUrl,
447474
pubkey: pubkey,
448475
channelId: channelId,
476+
generation: generation,
449477
members: members,
450478
);
451479
return members;

‎mobile/test/features/channels/channel_management_provider_test.dart‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import 'dart:async';
2+
13
import 'package:flutter_test/flutter_test.dart';
24
import 'package:buzz/features/channels/channel.dart';
35
import 'package:hooks_riverpod/hooks_riverpod.dart';
@@ -812,6 +814,91 @@ void main() {
812814
},
813815
);
814816

817+
for (final (label, olderAnswer) in [
818+
('a roster', [_heldRoster('bot', 2)]),
819+
('no roster event', <NostrEvent>[]),
820+
('an empty roster', [_emptyHeldRoster(2)]),
821+
]) {
822+
test('a superseded roster read answering with $label does not replace '
823+
'the offline roster', () async {
824+
final session = _HeldRosterRelaySession();
825+
final container = ProviderContainer(
826+
retry: (_, _) => null,
827+
overrides: [relaySessionProvider.overrideWith(() => session)],
828+
);
829+
addTearDown(container.dispose);
830+
final subscription = container.listen(
831+
channelMembersProvider(_channelId),
832+
(_, _) {},
833+
);
834+
addTearDown(subscription.close);
835+
Future<String> role() async => (await container.read(
836+
channelMembersProvider(_channelId).future,
837+
)).single.role;
838+
839+
expect(await role(), 'bot');
840+
await container.pump();
841+
842+
// Two roster updates arrive; the first read answers after the second.
843+
final older = Completer<List<NostrEvent>>();
844+
session.nextRead = older.future;
845+
session.emit(_heldRoster('bot', 2));
846+
await container.pump();
847+
final newer = Completer<List<NostrEvent>>();
848+
session.nextRead = newer.future;
849+
session.emit(_heldRoster('member', 3));
850+
await container.pump();
851+
newer.complete([_heldRoster('member', 3)]);
852+
expect(await role(), 'member');
853+
older.complete(olderAnswer);
854+
await container.pump();
855+
856+
session.disconnect();
857+
await container.pump();
858+
expect(await role(), 'member');
859+
});
860+
}
861+
862+
test(
863+
'a roster read torn down with no newer read still updates the offline roster',
864+
() async {
865+
final session = _HeldRosterRelaySession();
866+
final container = ProviderContainer(
867+
retry: (_, _) => null,
868+
overrides: [relaySessionProvider.overrideWith(() => session)],
869+
);
870+
addTearDown(container.dispose);
871+
var subscription = container.listen(
872+
channelMembersProvider(_channelId),
873+
(_, _) {},
874+
);
875+
Future<String> role() async => (await container.read(
876+
channelMembersProvider(_channelId).future,
877+
)).single.role;
878+
expect(await role(), 'bot');
879+
await container.pump();
880+
881+
// A roster update arrives; the user leaves before its read answers.
882+
final fresh = Completer<List<NostrEvent>>();
883+
session.nextRead = fresh.future;
884+
session.emit(_heldRoster('member', 2));
885+
await container.pump();
886+
subscription.close();
887+
await container.pump();
888+
fresh.complete([_heldRoster('member', 2)]);
889+
await container.pump();
890+
891+
session.disconnect();
892+
await container.pump();
893+
subscription = container.listen(
894+
channelMembersProvider(_channelId),
895+
(_, _) {},
896+
);
897+
addTearDown(subscription.close);
898+
expect(await role(), 'member');
899+
},
900+
);
901+
815902
test('keeps the member snapshot available during reconnect', () {
816903
final cachedMembers = [
817904
ChannelMember(
@@ -949,3 +1036,63 @@ class _ConnectionAwareRelaySession extends RelaySessionNotifier {
9491036
void Function(String message)? onClosed,
9501037
}) async => () {};
9511038
}
1039+
1040+
NostrEvent _heldRoster(String role, int version) => NostrEvent(
1041+
id: 'members-$version',
1042+
pubkey: 'owner',
1043+
createdAt: 1800000000 + version,
1044+
kind: 39002,
1045+
tags: [
1046+
['d', _channelId],
1047+
['p', _memberPubkey, '', role],
1048+
],
1049+
content: '',
1050+
sig: '',
1051+
);
1052+
1053+
NostrEvent _emptyHeldRoster(int version) => NostrEvent(
1054+
id: 'empty-members-$version',
1055+
pubkey: 'owner',
1056+
createdAt: 1800000000 + version,
1057+
kind: 39002,
1058+
tags: [
1059+
['d', _channelId],
1060+
],
1061+
content: '',
1062+
sig: '',
1063+
);
1064+
1065+
/// Answers each roster read with [nextRead] and delivers live roster updates
1066+
/// through [emit].
1067+
class _HeldRosterRelaySession extends RelaySessionNotifier {
1068+
Future<List<NostrEvent>> nextRead = Future.value([_heldRoster('bot', 1)]);
1069+
void Function(NostrEvent)? _listener;
1070+
1071+
@override
1072+
SessionState build() => const SessionState(status: SessionStatus.connected);
1073+
1074+
@override
1075+
Future<List<NostrEvent>> fetchHistory(
1076+
NostrFilter filter, {
1077+
Duration timeout = const Duration(seconds: 8),
1078+
}) => nextRead;
1079+
1080+
@override
1081+
Future<void Function()> subscribeWithStatus(
1082+
NostrFilter filter,
1083+
void Function(NostrEvent) onEvent, {
1084+
void Function(String message)? onClosed,
1085+
required void Function(RelaySubscriptionStatus status) onStatusChanged,
1086+
}) async {
1087+
_listener = onEvent;
1088+
onStatusChanged(RelaySubscriptionStatus.ready);
1089+
return () {
1090+
if (identical(_listener, onEvent)) _listener = null;
1091+
};
1092+
}
1093+
1094+
void emit(NostrEvent event) => _listener?.call(event);
1095+
1096+
void disconnect() =>
1097+
state = const SessionState(status: SessionStatus.disconnected);
1098+
}

0 commit comments

Comments
 (0)