Repository navigation
Expand file tree
/
Copy pathchannels_provider_test.dart
More file actions
4457 lines (4049 loc) · 153 KB
/
Copy pathchannels_provider_test.dart
File metadata and controls
4457 lines (4049 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'dart:io';
import 'dart:ui' as ui;
import 'package:fake_async/fake_async.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:buzz/features/activity/activity_page.dart';
import 'package:buzz/features/channels/channel_detail_page.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:hooks_riverpod/misc.dart';
import 'package:buzz/shared/channels/open_channel_directory_storage.dart';
import 'package:buzz/features/channels/channel_management_provider.dart';
import 'package:buzz/features/channels/channel_mutes/channel_mutes_provider.dart';
import 'package:buzz/features/channels/channel_mutes/channel_mutes_storage.dart';
import 'package:buzz/features/channels/channels_provider.dart';
import 'package:buzz/features/channels/unread_badge/observed_unread_event.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/read_state/read_state_provider.dart';
import 'package:buzz/shared/profile/user_cache_provider.dart';
import 'package:buzz/features/activity/activity_provider.dart';
import 'package:buzz/features/activity/inbox_item.dart';
import 'package:buzz/features/activity/inbox_read_state.dart';
import 'package:nostr/nostr.dart' as nostr;
part 'channels_provider_live_cases.dart';
part 'channels_provider_deletion_cases.dart';
part 'channels_provider_terminal_cases.dart';
part 'channels_provider_readiness_cases.dart';
part 'channels_provider_request_path_cases.dart';
part 'channels_provider_activity_cases.dart';
part 'channels_provider_join_cases.dart';
part 'channels_provider_saved_directory_cases.dart';
part 'channels_provider_thread_interest_cases.dart';
/// Tests for [ChannelsNotifier] in the pure-Nostr world.
///
/// The provider loads membership-backed channels first:
/// 1. paginated kind:39002 memberships tagged `#p:<my-pubkey>`
/// 2. kind:39000 metadata for those channel ids
/// then layers chunked live subscriptions on the `#h` tag. Browse channels
/// separately triggers paginated kind:39000 open-channel discovery.
///
/// Tests stub out the relay session by overriding [relaySessionProvider] with
/// a [_FakeRelaySession] that returns canned events from [fetchHistory] and
/// records [subscribe] calls so we can assert filter shapes and emit live
/// events on demand.
void main() {
_unreadReadinessCases();
_unreadDeletionCases();
_requestPathCases();
_threadActivityCases();
_confirmedJoinCases();
_savedDirectoryCases();
_threadInterestCases();
const myPk = 'me';
test(
'discovers open channels for a user with zero channel memberships',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadata: [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'staff', visibility: 'private'),
_meta(id: _channelD, name: 'DM', channelType: 'dm'),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
expect(session.directoryQueryFilters, isEmpty);
await container.read(channelsProvider.notifier).retryDirectory();
final channels = container.read(channelsProvider).requireValue;
expect(channels, hasLength(1));
expect(channels.single.id, _channelA);
expect(channels.single.isMember, isFalse);
expect(session.subscribeFilters, isEmpty);
expect(session.directoryQueryFilters, isNotEmpty);
},
);
test(
'the saved directory serves readers across launches and stays current',
() async {
final root = await Directory.systemTemp.createTemp('saved-directory');
addTearDown(() => root.delete(recursive: true));
final file = File('${root.path}/directory.json');
var now = DateTime.utc(2026, 1, 1);
var session = _FakeRelaySession(
memberships: const [],
metadata: [_meta(id: _channelA, name: 'general', createdAt: 100)],
);
final sessions = [session];
ProviderContainer launch() {
final container = _buildContainer(
session: session,
overrides: [
openChannelDirectoryStorageProvider.overrideWithValue(
OpenChannelDirectoryStorage(Future.value(file)),
),
channelDirectoryClockProvider.overrideWithValue(() => now),
],
);
addTearDown(container.dispose);
return container;
}
// The first page of each read; a read pages on with `until`.
List<int?> reads() => [
for (final session in sessions)
for (final filter in session.directoryQueryFilters)
if (filter.until == null) filter.since,
];
List<String> names(ProviderContainer container) => [
for (final channel in container.read(channelsProvider).requireValue)
channel.name,
];
// Saving runs behind the list update, on real file I/O.
Future<void> expectSaved(List<String> expected) async {
List<String> saved() {
if (!file.existsSync()) return const [];
final json = jsonDecode(file.readAsStringSync()) as Map;
return [
for (final meta in (json['metas'] as List).cast<Map>())
for (final tag in (meta['tags'] as List).cast<List>())
if (tag.first == 'name') tag[1] as String,
]..sort();
}
for (var i = 0; i < 200 && !listEquals(saved(), expected); i++) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
expect(saved(), expected);
}
// The first reader reads the whole directory and saves it.
var container = launch();
await container.read(channelsProvider.future);
var channels = container.read(channelsProvider.notifier);
await channels.ensureDirectoryLoaded();
await _settle();
expect(reads(), [null]);
expect(names(container), ['general']);
await expectSaved(['general']);
expect(await file.readAsString(), isNot(contains('"sig"')));
// More readers within a minute ask the relay nothing.
await channels.ensureDirectoryLoaded();
await _settle();
expect(reads(), [null]);
// A minute on, a reader asks only for changes, from a minute before the
// newest saved one: a rename and a new channel.
now = now.add(const Duration(minutes: 1));
session.metadata = [
_meta(id: _channelA, name: 'general-chat', createdAt: 150),
_meta(id: _channelB, name: 'fresh', createdAt: 200),
];
await channels.ensureDirectoryLoaded();
await _settle();
expect(reads().last, 100 - 60);
expect(names(container), unorderedEquals(['general-chat', 'fresh']));
await expectSaved(['fresh', 'general-chat']);
// A catch-up that brings back only held events (the overlap always
// returns the newest) neither rebuilds the list nor rewrites the file.
final list = container.read(channelsProvider).requireValue;
final stamp = DateTime(2020);
file.setLastModifiedSync(stamp);
now = now.add(const Duration(minutes: 1));
await channels.ensureDirectoryLoaded();
await _settle();
expect(reads().last, 200 - 60);
expect(
identical(container.read(channelsProvider).requireValue, list),
isTrue,
);
await Future<void>.delayed(const Duration(milliseconds: 50));
expect(file.lastModifiedSync(), stamp);
// After a relaunch the saved copy serves at once; the relay is asked only
// for changes since the newest saved one.
container.dispose();
now = now.add(const Duration(minutes: 5));
session = _FakeRelaySession(
memberships: const [],
metadata: session.metadata,
);
sessions.add(session);
container = launch();
await container.read(channelsProvider.future);
channels = container.read(channelsProvider.notifier);
final before = reads().length;
await channels.ensureDirectoryLoaded();
expect(names(container), unorderedEquals(['general-chat', 'fresh']));
await _settle();
expect(reads().skip(before), [200 - 60]);
// A channel that turned private is never in a catch-up, so it stays
// until the daily full read, which replaces the saved copy.
session.metadata = [
_meta(id: _channelA, name: 'general-chat', createdAt: 150),
];
now = now.add(const Duration(minutes: 1));
await channels.ensureDirectoryLoaded();
await _settle();
expect(names(container), unorderedEquals(['general-chat', 'fresh']));
now = now.add(savedDirectoryFullReadAge);
// A full read slower than the check interval is shared, not displaced:
// a reader opening a minute later asks the relay nothing more.
session.pauseNextDirectoryQuery();
await channels.ensureDirectoryLoaded();
await session.nextDirectoryQueryStarted;
final held = reads().length;
now = now.add(const Duration(minutes: 2));
await channels.ensureDirectoryLoaded();
await _settle();
expect(reads().length, held);
session.resumePausedDirectoryQuery();
await _settle();
expect(reads().last, isNull);
expect(names(container), ['general-chat']);
await expectSaved(['general-chat']);
// The quiet reads never showed search a loading state.
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.loaded,
);
// Opening a channel the relay no longer serves drops it at once, and a
// read already in flight, whose response predates the drop, does not
// bring it back.
now = now.add(const Duration(minutes: 1));
session.metadata = [
_meta(id: _channelA, name: 'general-chat', createdAt: 150),
_meta(id: _channelB, name: 'late', createdAt: 300),
];
session.pauseNextDirectoryQuery();
await channels.ensureDirectoryLoaded();
await session.nextDirectoryQueryStarted;
session.metadata = [];
await expectLater(
container.read(channelDetailsProvider(_channelA).future),
throwsException,
);
await _settle();
expect(names(container), isEmpty);
session.resumePausedDirectoryQuery();
await _settle();
// The shared full read advanced the full-read age, so this was a
// catch-up from the newest saved change.
expect(reads().last, 150 - 60);
expect(names(container), ['late']);
await expectSaved(['late']);
},
);
test(
'ensureDirectoryLoaded reads again after the community switches away and back',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadata: [_meta(id: _channelA, name: 'general')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
await container.read(channelsProvider.future);
final config = container.read(relayConfigProvider.notifier);
final communityA = container.read(relayConfigProvider).baseUrl;
await container.read(channelsProvider.notifier).ensureDirectoryLoaded();
expect(container.read(channelsProvider).requireValue.map((c) => c.id), [
_channelA,
]);
// Switch to B without loading its directory, then back to A. The switch
// drops A's cached directory, so A's earlier load no longer serves it.
config.update(baseUrl: 'https://community-b.example');
await container.read(channelsProvider.future);
config.update(baseUrl: communityA);
await container.read(channelsProvider.future);
final reads = session.directoryQueryFilters.length;
await container.read(channelsProvider.notifier).ensureDirectoryLoaded();
expect(session.directoryQueryFilters.length, greaterThan(reads));
expect(container.read(channelsProvider).requireValue.map((c) => c.id), [
_channelA,
]);
},
);
test('a directory load keeps latest-message times', () async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'discoverable'),
],
recentMessages: [
const NostrEvent(
id: 'm1',
pubkey: 'alice',
createdAt: 30,
kind: EventKind.streamMessageV2,
tags: [
['h', _channelA],
],
content: 'hi',
sig: 'sig',
),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
bool isLatest(List<NostrFilter> batch) =>
batch.isNotEmpty &&
batch.every(
(filter) =>
filter.since == null &&
filter.tags.containsKey('#h') &&
(filter.limit == 1 || filter.limit == 20),
);
await container.read(channelsProvider.future);
await _settle();
final latestReads = session.queryBatches.where(isLatest).length;
expect(latestReads, isPositive);
await container.read(channelsProvider.notifier).retryDirectory();
await _settle();
expect(session.queryBatches.where(isLatest), hasLength(latestReads));
final channels = container.read(channelsProvider).requireValue;
expect(channels.map((channel) => channel.id), [_channelB, _channelA]);
expect(
channels.firstWhere((channel) => channel.id == _channelA).lastMessageAt,
DateTime.fromMillisecondsSinceEpoch(30 * 1000, isUtc: true),
);
});
for (final deadlineFirst in [false, true]) {
_testWithClock('a directory load dates newly listed DMs'
'${deadlineFirst ? ' after a latest-message deadline' : ''}', (clock) {
NostrEvent message(String channelId, int at, String author) => NostrEvent(
id: '$channelId-$at',
pubkey: author,
createdAt: at,
kind: EventKind.streamMessageV2,
tags: [
['h', channelId],
],
content: 'hello',
sig: 'sig',
);
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [
_meta(id: _channelA, name: 'Alice', channelType: 'dm'),
_meta(id: _channelB, name: 'Bob', channelType: 'dm'),
],
recentMessages: [message(_channelA, 30, 'alice')],
enforceHistoryLimits: true,
);
final container = _buildContainer(session: session);
container.listen(channelsProvider, (_, _) {});
clock.flushMicrotasks();
DateTime? latest(String id) => container
.read(channelsProvider)
.requireValue
.singleWhere((channel) => channel.id == id)
.lastMessageAt;
// Another device opened DM B with an outgoing message, which unread
// catch-up skips. Search's directory load discovers B first.
session.memberships = [
_membership(_channelA, myPk),
_membership(_channelB, myPk),
];
session.recentMessages = [
message(_channelA, 30, 'alice'),
message(_channelB, 40, myPk),
];
if (deadlineFirst) {
session.latestBatchError = RelayException(
503,
'{"error":"query timed out"}',
);
}
container.read(channelsProvider.notifier).retryDirectory();
clock.flushMicrotasks();
if (deadlineFirst) {
expect(latest(_channelB), isNull);
// The retry after the deadline reads the whole list again.
session.latestBatchError = null;
clock.elapse(const Duration(seconds: 10));
}
expect(
latest(_channelB),
DateTime.fromMillisecondsSinceEpoch(40 * 1000, isUtc: true),
);
expect(
latest(_channelA),
DateTime.fromMillisecondsSinceEpoch(30 * 1000, isUtc: true),
);
container.dispose();
clock.elapse(const Duration(minutes: 10));
});
}
test('a directory load during the first channel load waits for it', () async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'discoverable'),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
final sub = container.listen(channelsProvider, (_, _) {});
addTearDown(sub.close);
// Search starts while the first load's member metadata is held.
session.pauseNextMemberMetadataQuery();
container.read(channelsProvider);
await session.nextMemberMetadataQueryStarted;
final directory = container
.read(channelsProvider.notifier)
.ensureDirectoryLoaded();
await _settle();
// The first load's reply arrives last. It must not replace the list.
session.resumePausedMemberMetadataQuery();
await directory;
await _settle();
final state = container.read(channelsProvider);
expect(state.hasError, isFalse);
expect(
state.requireValue.map((c) => c.id),
unorderedEquals([_channelA, _channelB]),
);
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.loaded,
);
});
test('paginates channel discovery with a composite cursor', () async {
final firstPage = List.generate(
500,
(index) => _meta(
id: '${index.toString().padLeft(8, '0')}-0000-4000-8000-000000000000',
name: 'channel-$index',
createdAt: 10,
),
);
final finalChannel = _meta(
id: '99999999-9999-4999-8999-999999999999',
name: 'last-page',
createdAt: 9,
);
final session = _FakeRelaySession(
memberships: const [],
metadataPages: [
firstPage,
[finalChannel],
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
await container.read(channelsProvider.notifier).retryDirectory();
final channels = container.read(channelsProvider).requireValue;
expect(channels, hasLength(501));
final directoryFilters = session.directoryQueryFilters;
expect(directoryFilters, hasLength(3));
expect(directoryFilters.first.until, isNull);
expect(directoryFilters.first.extensions, isEmpty);
expect(directoryFilters[1].until, firstPage.last.createdAt);
expect(directoryFilters[1].extensions['before_id'], firstPage.last.id);
expect(directoryFilters.last.until, finalChannel.createdAt);
expect(directoryFilters.last.extensions['before_id'], finalChannel.id);
});
test(
'paginates memberships when the relay caps responses below limit',
() async {
final firstPage = List.generate(
100,
(index) => _membership(
'${index.toString().padLeft(8, '0')}-0000-4000-8000-000000000000',
myPk,
),
);
final finalChannelId = '99999999-9999-4999-8999-999999999999';
final finalMembership = _membership(finalChannelId, myPk);
final session = _FakeRelaySession(
memberships: const [],
membershipPages: [
firstPage,
[finalMembership],
],
metadata: [_meta(id: finalChannelId, name: 'last-membership')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
final channels = await container.read(channelsProvider.future);
expect(channels.single.id, finalChannelId);
expect(channels.single.isMember, isTrue);
expect(session.membershipQueryFilters, hasLength(3));
expect(session.membershipQueryFilters.first.until, isNull);
expect(session.membershipQueryFilters.first.extensions, isEmpty);
expect(session.membershipQueryFilters[1].until, firstPage.last.createdAt);
expect(
session.membershipQueryFilters[1].extensions['before_id'],
firstPage.last.id,
);
expect(
session.membershipQueryFilters.last.extensions['before_id'],
finalMembership.id,
);
},
);
test('stops membership pagination when the relay repeats a page', () async {
final repeatedPage = List.generate(
500,
(index) => _membership(
'${index.toString().padLeft(8, '0')}-0000-4000-8000-000000000000',
myPk,
),
);
final session = _FakeRelaySession(
memberships: const [],
membershipPages: [repeatedPage],
repeatLastMembershipPage: true,
maxMembershipPageRequests: 2,
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
expect(session.membershipRequestCount, 2);
});
test('stops channel discovery when the relay repeats a full page', () async {
final repeatedPage = List.generate(
500,
(index) => _meta(
id: 'repeated-channel-$index',
name: 'repeated-$index',
createdAt: 10,
),
);
final session = _FakeRelaySession(
memberships: const [],
metadataPages: [repeatedPage],
repeatLastMetadataPage: true,
maxMetadataPageRequests: 2,
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
await container.read(channelsProvider.notifier).retryDirectory();
final channels = container.read(channelsProvider).requireValue;
expect(channels, hasLength(500));
expect(session.metadataPageRequestCount, 2);
});
test(
'directory page-cap failure is distinct from an empty directory',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadataPageBuilder: (pageIndex) => List.generate(
500,
(eventIndex) => _meta(
id: 'channel-$pageIndex-$eventIndex',
name: 'channel-$pageIndex-$eventIndex',
createdAt: 1000 - pageIndex,
),
),
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
await container.read(channelsProvider.notifier).retryDirectory();
expect(session.metadataPageRequestCount, 100);
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.error,
);
},
);
test(
'directory failure retains discovery while membership refreshes',
() async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'discoverable'),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(
(await container.read(
channelsProvider.future,
)).map((channel) => channel.id),
[_channelA],
);
await container.read(channelsProvider.notifier).retryDirectory();
expect(
container
.read(channelsProvider)
.requireValue
.map((channel) => channel.id),
unorderedEquals([_channelA, _channelB]),
);
session.memberships = [
_membership(_channelA, myPk),
_membership(_channelD, myPk),
];
session.metadata = [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'discoverable'),
_meta(id: _channelD, name: 'newly joined'),
];
session.directoryFailures = 1;
await container.read(channelsProvider.notifier).retryDirectory();
final refreshed = container.read(channelsProvider).requireValue;
expect(
refreshed.map((channel) => channel.id),
unorderedEquals([_channelA, _channelB, _channelD]),
);
expect(
refreshed.firstWhere((channel) => channel.id == _channelD).isMember,
isTrue,
);
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.error,
);
await container.read(channelsProvider.notifier).retryDirectory();
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.loaded,
);
},
);
test('directory retry failure retains the current channel list', () async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [_meta(id: _channelA, name: 'general')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
final initial = await container.read(channelsProvider.future);
session.membershipFailures = 1;
await container.read(channelsProvider.notifier).retryDirectory();
expect(container.read(channelsProvider).requireValue, initial);
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.error,
);
});
test(
'a directory retry clears an earlier failure before it yields',
() async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [_meta(id: _channelA, name: 'general')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
await container.read(channelsProvider.future);
session.membershipFailures = 1;
await container.read(channelsProvider.notifier).retryDirectory();
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.error,
);
// A refresh that retires this attempt in the same microtask drain must
// not leave the old error to be read as its result.
final retry = container.read(channelsProvider.notifier).retryDirectory();
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.idle,
);
await retry;
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.loaded,
);
},
);
for (final rebuild in [false, true]) {
test(
'${rebuild ? 'Same-scope rebuild' : 'Ordinary refresh'} settles a superseded directory load for retry',
() async {
final session = _FakeRelaySession(
memberships: [_membership(_channelA, myPk)],
metadata: [
_meta(id: _channelA, name: 'general'),
_meta(id: _channelB, name: 'discoverable'),
],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(
(await container.read(
channelsProvider.future,
)).map((channel) => channel.id),
[_channelA],
);
session.pauseNextDirectoryQuery();
final directory = container
.read(channelsProvider.notifier)
.retryDirectory();
await session.nextDirectoryQueryStarted;
if (rebuild) {
// A same-scope configuration rebuild can overlap an in-flight
// directory request when onboarding settles its community providers.
final config = container.read(relayConfigProvider);
container
.read(relayConfigProvider.notifier)
.update(baseUrl: config.baseUrl, nsec: config.nsec);
await container.read(channelsProvider.future);
} else {
await container.read(channelsProvider.notifier).refresh();
}
session.resumePausedDirectoryQuery();
await directory;
await _settle();
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.idle,
);
expect(
container
.read(channelsProvider)
.requireValue
.map((channel) => channel.id),
[_channelA],
);
await container.read(channelsProvider.notifier).retryDirectory();
expect(
container.read(channelDirectoryLoadStatusProvider).status,
ChannelDirectoryLoadStatus.loaded,
);
expect(
container
.read(channelsProvider)
.requireValue
.map((channel) => channel.id),
unorderedEquals([_channelA, _channelB]),
);
},
);
}
test('refresh disposed before directory settlement writes nothing', () async {
final session = _FakeRelaySession(memberships: const []);
final container = _buildContainer(session: session);
await container.read(channelsProvider.future);
final refresh = container.read(channelsProvider.notifier).refresh();
container.dispose();
await expectLater(refresh, completes);
});
test(
'community switch discards a stale directory success from the old relay',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadata: [_meta(id: _channelA, name: 'community-a-open')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
session.pauseNextDirectoryQuery();
final staleDirectory = container
.read(channelsProvider.notifier)
.retryDirectory();
await session.nextDirectoryQueryStarted;
// Switch communities while community A's directory response is paused.
session.memberships = [_membership(_channelB, myPk)];
session.metadata = [_meta(id: _channelB, name: 'community-b-general')];
container
.read(relayConfigProvider.notifier)
.update(baseUrl: 'https://community-b.example');
await container.read(channelsProvider.future);
session.resumePausedDirectoryQuery();
await staleDirectory;
await _settle();
final ids = container
.read(channelsProvider)
.requireValue
.map((channel) => channel.id);
expect(ids, isNot(contains(_channelA)));
expect(ids, contains(_channelB));
expect(
container.read(channelDirectoryLoadStatusProvider).scope,
isNot(
channelDirectoryScope(
'https://community-b.example',
container.read(myPubkeyProvider),
),
),
);
},
);
test(
'community switch discards a stale directory failure from the old relay',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadata: [_meta(id: _channelA, name: 'community-a-open')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
session.pauseNextDirectoryQuery();
final staleDirectory = container
.read(channelsProvider.notifier)
.retryDirectory();
await session.nextDirectoryQueryStarted;
session.memberships = [_membership(_channelB, myPk)];
session.metadata = [_meta(id: _channelB, name: 'community-b-general')];
container
.read(relayConfigProvider.notifier)
.update(baseUrl: 'https://community-b.example');
await container.read(channelsProvider.future);
// Community A's directory request fails after the switch.
session.directoryFailures = 1;
session.resumePausedDirectoryQuery();
await staleDirectory;
await _settle();
final ids = container
.read(channelsProvider)
.requireValue
.map((channel) => channel.id);
expect(ids, contains(_channelB));
expect(
container.read(channelDirectoryLoadStatusProvider).scope,
isNot(
channelDirectoryScope(
'https://community-b.example',
container.read(myPubkeyProvider),
),
),
);
},
);
test(
'identity switch discards a stale directory success from the old identity',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadata: [_meta(id: _channelA, name: 'first-identity-open')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
session.pauseNextDirectoryQuery();
final staleDirectory = container
.read(channelsProvider.notifier)
.retryDirectory();
await session.nextDirectoryQueryStarted;
// Switch signing identity while the first identity's response is paused.
session.memberships = [_membership(_channelB, _otherPk)];
session.metadata = [_meta(id: _channelB, name: 'second-identity-joined')];
container.read(_testPubkeyProvider.notifier).set(_otherPk);
await container.read(channelsProvider.future);
session.resumePausedDirectoryQuery();
await staleDirectory;
await _settle();
final ids = container
.read(channelsProvider)
.requireValue
.map((channel) => channel.id);
expect(ids, isNot(contains(_channelA)));
expect(ids, contains(_channelB));
},
);
test(
'identity switch discards a stale directory failure from the old identity',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadata: [_meta(id: _channelA, name: 'first-identity-open')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
session.pauseNextDirectoryQuery();
final staleDirectory = container
.read(channelsProvider.notifier)
.retryDirectory();
await session.nextDirectoryQueryStarted;
session.memberships = [_membership(_channelB, _otherPk)];
session.metadata = [_meta(id: _channelB, name: 'second-identity-joined')];
container.read(_testPubkeyProvider.notifier).set(_otherPk);
await container.read(channelsProvider.future);
session.directoryFailures = 1;
session.resumePausedDirectoryQuery();
await staleDirectory;
await _settle();
expect(
container
.read(channelsProvider)
.requireValue
.map((channel) => channel.id),
contains(_channelB),
);
},
);
test(
'community switch after directory success discards the late refresh',
() async {
final session = _FakeRelaySession(
memberships: const [],
metadata: [_meta(id: _channelA, name: 'community-a-open')],
);
final container = _buildContainer(session: session);
addTearDown(container.dispose);
expect(await container.read(channelsProvider.future), isEmpty);
// Community A now has a joined channel, so the directory-triggered
// refresh reaches the live-subscribe step and parks there. That await is
// AFTER the loader's own directory fence, which is the window this arm