mirror of
https://github.com/block/buzz.git
synced 2026-11-26 03:01:38 +00:00
[#9444](https://github.com/block/buzz/pull/9444) narrows the live presence subscription (kind 20001) to the people the app has shown this session. That set only grows, so scrolling through a long DM list or opening many profiles keeps receiving presence for people who are no longer on screen, and each new person reopens the subscription with everyone seen so far. This was raised in [Jude's review](https://github.com/block/buzz/pull/9444#pullrequestreview-5896221680). With this change, presence follows only who is on screen now: - `track` returns a release callback. DM rows and profile sheets release when they unmount. Counts are per person, so someone shown in a DM row and an open profile sheet stays followed until both are gone. - A person nobody has shown for at least 30 seconds is retired: dropped from the tracked set and the cache, and the live subscription is replaced with one for the people still shown. A sweep every 30 seconds retires everyone whose own 30 seconds are up, so each person stays followed for 30 to 60 seconds after their release and the subscription narrows at most once per 30 seconds. Scrolling back within 30 seconds keeps the current subscription. - A read that started before someone was retired doesn't fill in their presence if they are shown again; they wait for a read of their own. - When nobody is shown, the stream closes, and the next person shown opens a new one immediately. - Switching communities keeps following people still on screen, instead of dropping everyone. ### Regressions - **Mention picker ranking.** The picker reads the presence cache without tracking anyone itself, so it ranks by presence only for people currently on screen (before, also for anyone shown earlier in the session). Keeping a retired person's last value would show stale presence, which is worse. - **Dot pop-in.** A retired person's dot is missing when they come back (scrolling back after 30 seconds, or switching the Home filter to Solo and back after 30 seconds) until the replacement subscription is ready and their snapshot read returns. On a slow link that can take seconds. Before, the dot stayed for the whole session. - **Network.** A retirement costs one replacement REQ and a CLOSE, at most once per 30 seconds of scrolling. A person shown again after being retired costs one snapshot read, the same as the first time they were shown. - **Reliability.** Narrowing uses #9444's replacement path (the old stream stays until the new one is ready), so a failed narrowing keeps the wider stream and the poll retries it. ### Validation iPhone 12 mini on Builderlab (measured on [bda9e214f](https://github.com/block/buzz/commit/bda9e214f), before the sweep change), cold launch, scroll the Home list to the bottom and back to the top, then 60 s idle: | | #9444 head | This PR | | --- | --- | --- | | Live presence authors at the end | 37 (only grows) | 1 (37 at the bottom, then 11, then 1) | | Presence events while idle (60 s) | 29 (10.7 KB) | 0 | | Presence REQs during the run | 36 | 37 | Presence dots still show on the DM rows visible at the bottom of the list. Both heads still reopen the subscription once per newly shown person while scrolling (36 swaps for 37 people); batching those during a fling would be the next bound, and is not part of this PR. Added tests: - A person shown in two places stays followed until both release. Released people leave the subscription only after the delay, and their late live events are ignored. - Showing someone again within the delay keeps the same subscription and their cached presence. - Releasing everyone closes the stream, and the next person shown gets a new subscription and a snapshot read right away. - Scrolling 500 rows past a window of 10 leaves a subscription for exactly the last 10, with exactly two replacement opens after scrolling stops (the sweeps 30 s apart). - A person released 29 seconds after another keeps their subscription and cached presence when the first one is retired, and is retired at a later sweep. - A person retired while their snapshot is in flight stays absent. - A read started a second before someone is retired doesn't fill them in once they're shown again; the other people in that read keep their results, and the person's own read does. - Production seam: removing a DM row from the Home list stops following that person after the delay (the stream closes and the cache empties). Each guard was mutation-checked: removing it fails at least one of these tests. Changed test: the community-switch snapshot test now expects people still on screen to be read in the new community. Full mobile suite: 4857 passed, 71 skipped (onca0066de3, after rebasing onto main). --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
683 lines
25 KiB
Dart
683 lines
25 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:fake_async/fake_async.dart';
|
|
import 'package:flutter/widgets.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
import 'package:buzz/features/profile/presence_cache_provider.dart';
|
|
import 'package:buzz/shared/relay/relay.dart';
|
|
|
|
/// Live-stream behavior alongside the authenticated snapshot backstop.
|
|
void main() {
|
|
test('WS presence event updates cache for tracked pubkey', () async {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
|
|
// Initialize the notifier (triggers build → subscribes to WS).
|
|
container.read(presenceCacheProvider);
|
|
await _pumpEventQueue();
|
|
|
|
// Track alice, then emit her initial 'online' status.
|
|
container.read(presenceCacheProvider.notifier).track(['alice']);
|
|
await _pumpEventQueue();
|
|
relaySession.emit(_presence('alice', 'online'));
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
|
|
// Simulate a WS presence event: alice goes away.
|
|
relaySession.emit(_presence('alice', 'away'));
|
|
expect(container.read(presenceCacheProvider)['alice'], 'away');
|
|
});
|
|
|
|
test('WS presence event ignores untracked pubkeys', () async {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
|
|
container.read(presenceCacheProvider);
|
|
await _pumpEventQueue();
|
|
|
|
// Track only alice.
|
|
container.read(presenceCacheProvider.notifier).track(['alice']);
|
|
await _pumpEventQueue();
|
|
|
|
// Emit event for bob (untracked).
|
|
relaySession.emit(_presence('bob', 'online'));
|
|
|
|
// Bob should NOT appear in the cache.
|
|
expect(container.read(presenceCacheProvider).containsKey('bob'), isFalse);
|
|
});
|
|
|
|
test('WS presence event ignores invalid status values', () async {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
|
|
container.read(presenceCacheProvider);
|
|
await _pumpEventQueue();
|
|
|
|
container.read(presenceCacheProvider.notifier).track(['alice']);
|
|
await _pumpEventQueue();
|
|
relaySession.emit(_presence('alice', 'online'));
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
|
|
// Emit event with garbage status — should be rejected.
|
|
relaySession.emit(_presence('alice', 'garbage-status'));
|
|
|
|
// Status should remain 'online'.
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
});
|
|
|
|
test('WS presence event skips no-op updates', () async {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
|
|
container.read(presenceCacheProvider);
|
|
await _pumpEventQueue();
|
|
|
|
container.read(presenceCacheProvider.notifier).track(['alice']);
|
|
await _pumpEventQueue();
|
|
relaySession.emit(_presence('alice', 'online'));
|
|
|
|
// Listen for state changes after initial setup.
|
|
var stateChangeCount = 0;
|
|
container.listen(presenceCacheProvider, (prev, next) => stateChangeCount++);
|
|
|
|
// Emit event with same status as current.
|
|
relaySession.emit(_presence('alice', 'online'));
|
|
|
|
// No state change should occur — it's a no-op.
|
|
expect(stateChangeCount, 0);
|
|
});
|
|
|
|
test('subscribes to kind:20001 for tracked pubkeys only', () async {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
|
|
container.read(presenceCacheProvider);
|
|
await _pumpEventQueue();
|
|
// Nothing is tracked, so nothing is worth a community-wide stream.
|
|
expect(relaySession.filters, isEmpty);
|
|
|
|
container.read(presenceCacheProvider.notifier).track(['alice']);
|
|
await _pumpEventQueue();
|
|
expect(relaySession.filters, hasLength(1));
|
|
expect(relaySession.filters.single.kinds, [EventKind.presenceUpdate]);
|
|
expect(relaySession.filters.single.authors, ['alice']);
|
|
expect(relaySession.filters.single.limit, 0);
|
|
|
|
// A newly tracked key replaces the subscription with a wider one.
|
|
container.read(presenceCacheProvider.notifier).track(['bob', 'alice']);
|
|
await _pumpEventQueue();
|
|
expect(relaySession.filters, hasLength(1));
|
|
expect(relaySession.filters.single.authors, ['alice', 'bob']);
|
|
relaySession.emit(_presence('bob', 'online'));
|
|
expect(container.read(presenceCacheProvider)['bob'], 'online');
|
|
});
|
|
|
|
test(
|
|
'a first subscription still retrying when it opens waits for ready',
|
|
() async {
|
|
final relaySession = _RecordingRelaySessionNotifier()..autoReady = false;
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
|
|
container.read(presenceCacheProvider);
|
|
container.read(presenceCacheProvider.notifier).track(['alice']);
|
|
await _pumpEventQueue();
|
|
final subscription = relaySession.subscriptions.single;
|
|
// Bob is tracked while alice's first subscription is still opening.
|
|
container.read(presenceCacheProvider.notifier).track(['bob']);
|
|
await _pumpEventQueue();
|
|
expect(relaySession.subscriptions, [subscription]);
|
|
|
|
// A retryable CLOSED releases the open before the stream is live, so a
|
|
// snapshot now could miss a change before the retry's EOSE.
|
|
relaySession.snapshot['alice'] = 'online';
|
|
subscription.retrying();
|
|
await _pumpEventQueue();
|
|
expect(relaySession.queried, isEmpty);
|
|
|
|
// Its recovery reads both and widens to cover bob live.
|
|
subscription.ready();
|
|
await _pumpEventQueue();
|
|
expect(
|
|
relaySession.queried.expand((keys) => keys),
|
|
containsAll(['alice', 'bob']),
|
|
);
|
|
expect(relaySession.subscriptions.last.filter.authors, ['alice', 'bob']);
|
|
expect(container.read(presenceCacheProvider)['alice'], 'online');
|
|
},
|
|
);
|
|
|
|
test('the poll recovers from a replacement the relay never answers', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
notifier.track(['alice']);
|
|
time.elapse(Duration.zero);
|
|
final first = relaySession.subscriptions.single;
|
|
|
|
// Bob's replacement opens on the timeout and never gets EOSE or CLOSED.
|
|
relaySession.autoReady = false;
|
|
notifier.track(['bob']);
|
|
time.elapse(Duration.zero);
|
|
final lost = relaySession.subscriptions.last;
|
|
lost.open();
|
|
time.elapse(Duration.zero);
|
|
|
|
// The next poll drops it and widens again; alice's stream stays.
|
|
time.elapse(const Duration(seconds: 60));
|
|
expect(relaySession.subscriptions, hasLength(2));
|
|
expect(relaySession.subscriptions, isNot(contains(lost)));
|
|
final retry = relaySession.subscriptions.last;
|
|
expect(retry.filter.authors, ['alice', 'bob']);
|
|
retry.open();
|
|
time.elapse(Duration.zero);
|
|
|
|
// That one is lost too, and then alice's stream closes for good.
|
|
first.closeTerminal();
|
|
time.elapse(Duration.zero);
|
|
expect(relaySession.subscriptions, [retry]);
|
|
|
|
// One poll later a fresh subscription covers everyone and reads them.
|
|
relaySession.autoReady = true;
|
|
relaySession.queried.clear();
|
|
time.elapse(const Duration(seconds: 60));
|
|
expect(relaySession.subscriptions, hasLength(1));
|
|
expect(relaySession.subscriptions.single.filter.authors, [
|
|
'alice',
|
|
'bob',
|
|
]);
|
|
expect(
|
|
relaySession.queried.expand((keys) => keys),
|
|
containsAll(['alice', 'bob']),
|
|
);
|
|
expect(container.read(presenceCacheProvider), {
|
|
'alice': 'offline',
|
|
'bob': 'offline',
|
|
});
|
|
});
|
|
});
|
|
|
|
test('a released key leaves the subscription once nobody shows it', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
// Alice is shown in two places, Bob in one.
|
|
final aliceRow = notifier.track(['alice']);
|
|
final aliceSheet = notifier.track(['alice']);
|
|
final bobRow = notifier.track(['bob']);
|
|
time.elapse(Duration.zero);
|
|
expect(relaySession.subscriptions.last.filter.authors, ['alice', 'bob']);
|
|
final wide = relaySession.subscriptions.last;
|
|
|
|
aliceRow();
|
|
bobRow();
|
|
bobRow(); // a second call releases nothing more
|
|
time.elapse(
|
|
PresenceCacheNotifier.releaseDelay - const Duration(seconds: 1),
|
|
);
|
|
expect(relaySession.subscriptions, [wide]);
|
|
|
|
time.elapse(const Duration(seconds: 1));
|
|
expect(relaySession.subscriptions, hasLength(1));
|
|
expect(relaySession.subscriptions.single.filter.authors, ['alice']);
|
|
expect(container.read(presenceCacheProvider).keys, ['alice']);
|
|
|
|
relaySession.emit(_presence('bob', 'online'));
|
|
relaySession.emit(_presence('alice', 'online'));
|
|
expect(container.read(presenceCacheProvider), {'alice': 'online'});
|
|
aliceSheet();
|
|
});
|
|
});
|
|
|
|
test('a key shown again within the delay keeps its subscription', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
notifier.track(['alice']);
|
|
final bob = notifier.track(['bob']);
|
|
time.elapse(Duration.zero);
|
|
relaySession.emit(_presence('bob', 'online'));
|
|
final wide = relaySession.subscriptions.single;
|
|
|
|
// Bob scrolls off and back before the delay ends.
|
|
bob();
|
|
time.elapse(const Duration(seconds: 10));
|
|
notifier.track(['bob']);
|
|
time.elapse(PresenceCacheNotifier.releaseDelay);
|
|
expect(relaySession.subscriptions, [wide]);
|
|
expect(container.read(presenceCacheProvider)['bob'], 'online');
|
|
});
|
|
});
|
|
|
|
test('each key keeps the full delay after its own release', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
final alice = notifier.track(['alice']);
|
|
final bob = notifier.track(['bob']);
|
|
notifier.track(['carol']);
|
|
relaySession.snapshot['bob'] = 'online';
|
|
time.elapse(Duration.zero);
|
|
|
|
alice();
|
|
time.elapse(const Duration(seconds: 29));
|
|
bob();
|
|
time.elapse(const Duration(seconds: 1));
|
|
// Alice's delay is over; Bob was released a second ago.
|
|
expect(relaySession.subscriptions.single.filter.authors, [
|
|
'bob',
|
|
'carol',
|
|
]);
|
|
expect(container.read(presenceCacheProvider)['bob'], 'online');
|
|
|
|
// Showing Bob again costs nothing.
|
|
final opens = relaySession.opens;
|
|
final bobAgain = notifier.track(['bob']);
|
|
time.elapse(PresenceCacheNotifier.releaseDelay * 2);
|
|
expect(relaySession.opens, opens);
|
|
expect(container.read(presenceCacheProvider)['bob'], 'online');
|
|
|
|
// Released for good, Bob goes at the sweep after his delay.
|
|
bobAgain();
|
|
time.elapse(PresenceCacheNotifier.releaseDelay * 2);
|
|
expect(relaySession.subscriptions.single.filter.authors, ['carol']);
|
|
expect(container.read(presenceCacheProvider), isNot(contains('bob')));
|
|
});
|
|
});
|
|
|
|
test('a read from before retirement does not fill a key shown again', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
final alice = notifier.track(['alice']);
|
|
notifier.track(['carol']);
|
|
time.elapse(Duration.zero);
|
|
time.elapse(const Duration(seconds: 31));
|
|
alice();
|
|
relaySession.holdQueries = true;
|
|
// The poll's read starts a second before Alice is retired.
|
|
time.elapse(const Duration(seconds: 29));
|
|
expect(relaySession.held, hasLength(1));
|
|
time.elapse(const Duration(seconds: 1));
|
|
expect(relaySession.subscriptions.single.filter.authors, ['carol']);
|
|
|
|
notifier.track(['alice']);
|
|
time.elapse(Duration.zero);
|
|
relaySession.held.removeAt(0).complete([
|
|
_presence('alice', 'online'),
|
|
_presence('carol', 'online'),
|
|
]);
|
|
time.elapse(Duration.zero);
|
|
// Carol keeps her answer; Alice waits for a read of her own.
|
|
expect(container.read(presenceCacheProvider), {'carol': 'online'});
|
|
expect(relaySession.queried.last, ['alice']);
|
|
relaySession.held.removeAt(0).complete([_presence('alice', 'away')]);
|
|
time.elapse(Duration.zero);
|
|
expect(container.read(presenceCacheProvider), {
|
|
'alice': 'away',
|
|
'carol': 'online',
|
|
});
|
|
});
|
|
});
|
|
|
|
test('releasing everyone closes the stream until someone is shown', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
final alice = notifier.track(['alice']);
|
|
time.elapse(Duration.zero);
|
|
alice();
|
|
time.elapse(PresenceCacheNotifier.releaseDelay);
|
|
expect(relaySession.subscriptions, isEmpty);
|
|
expect(container.read(presenceCacheProvider), isEmpty);
|
|
|
|
relaySession.queried.clear();
|
|
notifier.track(['carol']);
|
|
time.elapse(Duration.zero);
|
|
expect(relaySession.subscriptions.single.filter.authors, ['carol']);
|
|
expect(relaySession.queried.expand((keys) => keys), ['carol']);
|
|
});
|
|
});
|
|
|
|
test('scrolling a long list keeps only the rows still shown', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
// 500 rows scroll past a window of 10.
|
|
final shown = <void Function()>[];
|
|
for (var row = 0; row < 500; row++) {
|
|
shown.add(notifier.track(['p${row.toString().padLeft(3, '0')}']));
|
|
if (shown.length > 10) shown.removeAt(0)();
|
|
time.elapse(const Duration(milliseconds: 50));
|
|
}
|
|
// Rows released over the last 25 s go in two narrowings, 30 s apart.
|
|
final opensWhileScrolling = relaySession.opens;
|
|
time.elapse(PresenceCacheNotifier.releaseDelay * 2);
|
|
expect(relaySession.opens - opensWhileScrolling, 2);
|
|
expect(relaySession.subscriptions, hasLength(1));
|
|
expect(relaySession.subscriptions.single.filter.authors, [
|
|
for (var row = 490; row < 500; row++) 'p$row',
|
|
]);
|
|
});
|
|
});
|
|
|
|
test('the poll still reads a live stream while its widening fails', () {
|
|
fakeAsync((time) {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
|
|
container.read(presenceCacheProvider);
|
|
notifier.track(['alice']);
|
|
time.elapse(Duration.zero);
|
|
relaySession.emit(_presence('alice', 'online'));
|
|
relaySession.autoReady = false;
|
|
notifier.track(['bob']);
|
|
time.elapse(Duration.zero);
|
|
relaySession.subscriptions.last.retrying();
|
|
time.elapse(Duration.zero);
|
|
expect(relaySession.subscriptions, hasLength(1));
|
|
|
|
// Alice's lease expired; each poll retries the widening and still
|
|
// reads her, so she is corrected to offline.
|
|
relaySession.queried.clear();
|
|
time.elapse(const Duration(seconds: 60));
|
|
expect(relaySession.subscriptions, hasLength(2));
|
|
expect(relaySession.queried.expand((keys) => keys), contains('alice'));
|
|
expect(container.read(presenceCacheProvider)['alice'], 'offline');
|
|
});
|
|
});
|
|
|
|
test(
|
|
'a wider subscription replaces the live one only once it is ready',
|
|
() async {
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
final notifier = container.read(presenceCacheProvider.notifier);
|
|
Map<String, String> cache() => container.read(presenceCacheProvider);
|
|
|
|
container.read(presenceCacheProvider);
|
|
notifier.track(['alice']);
|
|
await _pumpEventQueue();
|
|
relaySession.emit(_presence('alice', 'online'));
|
|
expect(cache(), {'alice': 'online'});
|
|
final first = relaySession.subscriptions.single;
|
|
|
|
// Tracking bob opens a replacement; alice's stream keeps delivering.
|
|
relaySession.autoReady = false;
|
|
notifier.track(['bob']);
|
|
await _pumpEventQueue();
|
|
final retried = relaySession.subscriptions.last;
|
|
expect(retried.filter.authors, ['alice', 'bob']);
|
|
relaySession.emit(_presence('alice', 'away'));
|
|
expect(cache()['alice'], 'away');
|
|
|
|
// A second track while one is pending does not open a third.
|
|
notifier.track(['carol']);
|
|
await _pumpEventQueue();
|
|
expect(relaySession.subscriptions, [first, retried]);
|
|
|
|
// A retryable CLOSED on the replacement retires it, not alice's stream,
|
|
// and her status stays on screen.
|
|
retried.retrying();
|
|
await _pumpEventQueue();
|
|
expect(relaySession.subscriptions, [first]);
|
|
expect(cache()['alice'], 'away');
|
|
relaySession.emit(_presence('alice', 'online', 1));
|
|
expect(cache()['alice'], 'online');
|
|
|
|
// The next replacement resolves on the timeout, before its EOSE.
|
|
notifier.track(['dave']);
|
|
await _pumpEventQueue();
|
|
final slow = relaySession.subscriptions.last;
|
|
expect(slow.filter.authors, ['alice', 'bob', 'carol', 'dave']);
|
|
slow.open();
|
|
await _pumpEventQueue();
|
|
expect(relaySession.subscriptions, [first, slow]);
|
|
|
|
// Bob went offline after any earlier snapshot of him and before the new
|
|
// stream covered him. Its late EOSE promotes it without blanking alice,
|
|
// and the keys it newly covers are read again.
|
|
relaySession.snapshot['bob'] = 'offline';
|
|
relaySession.queried.clear();
|
|
slow.ready();
|
|
await _pumpEventQueue();
|
|
expect(relaySession.subscriptions, [slow]);
|
|
expect(
|
|
relaySession.queried.expand((keys) => keys),
|
|
containsAll(['bob', 'carol', 'dave']),
|
|
);
|
|
expect(
|
|
relaySession.queried.expand((keys) => keys),
|
|
isNot(contains('alice')),
|
|
);
|
|
expect(cache()['alice'], 'online');
|
|
expect(cache()['bob'], 'offline');
|
|
|
|
// A replacement that fails outright leaves the live stream and cache.
|
|
notifier.track(['erin']);
|
|
await _pumpEventQueue();
|
|
relaySession.subscriptions.last.fail();
|
|
await _pumpEventQueue();
|
|
expect(relaySession.subscriptions, [slow]);
|
|
expect(cache()['alice'], 'online');
|
|
relaySession.emit(_presence('alice', 'away', 1));
|
|
expect(cache()['alice'], 'away');
|
|
},
|
|
);
|
|
|
|
test('WS event uses pubkey variable, not literal string', () async {
|
|
// Regression test for the map key bug where `{...state, pubkey: status}`
|
|
// used the literal string "pubkey" instead of the variable's value.
|
|
final relaySession = _RecordingRelaySessionNotifier();
|
|
final container = _buildContainer(relaySession: relaySession);
|
|
addTearDown(container.dispose);
|
|
|
|
container.read(presenceCacheProvider);
|
|
await _pumpEventQueue();
|
|
|
|
container.read(presenceCacheProvider.notifier).track([
|
|
'deadbeef',
|
|
'cafebabe',
|
|
]);
|
|
await _pumpEventQueue();
|
|
|
|
// Seed cafebabe -> offline, then set deadbeef online.
|
|
relaySession.emit(_presence('cafebabe', 'offline'));
|
|
relaySession.emit(_presence('deadbeef', 'online'));
|
|
|
|
final cache = container.read(presenceCacheProvider);
|
|
// deadbeef should be online (the actual pubkey, not a literal "pubkey" key).
|
|
expect(cache['deadbeef'], 'online');
|
|
// cafebabe should still be offline (not clobbered).
|
|
expect(cache['cafebabe'], 'offline');
|
|
// There should be no literal "pubkey" key in the map.
|
|
expect(cache.containsKey('pubkey'), isFalse);
|
|
});
|
|
}
|
|
|
|
NostrEvent _presence(String pubkey, String status, [int seq = 0]) => NostrEvent(
|
|
id: 'evt-$pubkey-$status-$seq',
|
|
pubkey: pubkey,
|
|
createdAt: 1000,
|
|
kind: EventKind.presenceUpdate,
|
|
tags: const [],
|
|
content: status,
|
|
sig: 'sig',
|
|
);
|
|
|
|
Future<void> _pumpEventQueue() async {
|
|
await Future<void>.delayed(Duration.zero);
|
|
await Future<void>.delayed(Duration.zero);
|
|
}
|
|
|
|
ProviderContainer _buildContainer({
|
|
required _RecordingRelaySessionNotifier relaySession,
|
|
}) {
|
|
return ProviderContainer(
|
|
overrides: [
|
|
appLifecycleProvider.overrideWith(() => _FakeAppLifecycleNotifier()),
|
|
relaySessionProvider.overrideWith(() => relaySession),
|
|
],
|
|
);
|
|
}
|
|
|
|
class _RecordingRelaySessionNotifier extends RelaySessionNotifier {
|
|
final List<NostrFilter> filters = [];
|
|
final List<_FakeSubscription> subscriptions = [];
|
|
final List<List<String>> queried = [];
|
|
final Map<String, String> snapshot = {};
|
|
|
|
/// Every subscription ever opened, closed ones included.
|
|
int opens = 0;
|
|
|
|
/// When true, each read waits in [held] for the test to answer it.
|
|
bool holdQueries = false;
|
|
final List<Completer<List<NostrEvent>>> held = [];
|
|
|
|
/// When false, each subscription waits for the test to drive it.
|
|
bool autoReady = true;
|
|
|
|
@override
|
|
SessionState build() => const SessionState(status: SessionStatus.connected);
|
|
|
|
@override
|
|
Future<void Function()> subscribeWithStatus(
|
|
NostrFilter filter,
|
|
void Function(NostrEvent) onEvent, {
|
|
void Function(String message)? onClosed,
|
|
required void Function(RelaySubscriptionStatus) onStatusChanged,
|
|
bool resumeSince = true,
|
|
}) {
|
|
final subscription = _FakeSubscription(
|
|
this,
|
|
filter,
|
|
onEvent,
|
|
onClosed,
|
|
onStatusChanged,
|
|
);
|
|
filters.add(filter);
|
|
subscriptions.add(subscription);
|
|
opens++;
|
|
if (autoReady) {
|
|
// Like an EOSE that arrives before the open future resolves.
|
|
onStatusChanged(RelaySubscriptionStatus.ready);
|
|
subscription.open();
|
|
}
|
|
return subscription.opened.future;
|
|
}
|
|
|
|
@override
|
|
Future<List<NostrEvent>> queryRelay(
|
|
List<NostrFilter> filters, {
|
|
Duration timeout = const Duration(seconds: 8),
|
|
}) async {
|
|
final authors = filters.single.authors!;
|
|
queried.add(authors);
|
|
if (holdQueries) {
|
|
final read = Completer<List<NostrEvent>>();
|
|
held.add(read);
|
|
return read.future;
|
|
}
|
|
return [
|
|
for (final key in authors)
|
|
if (snapshot[key] case final status?) _presence(key, status),
|
|
];
|
|
}
|
|
|
|
/// Emit an event synchronously to all live subscribers.
|
|
void emit(NostrEvent event) {
|
|
for (final subscription in List.of(subscriptions)) {
|
|
if (subscription.live) subscription.onEvent(event);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// One subscription whose open, status and failure order the test controls.
|
|
class _FakeSubscription {
|
|
_FakeSubscription(
|
|
this.relay,
|
|
this.filter,
|
|
this.onEvent,
|
|
this.onClosed,
|
|
this.onStatusChanged,
|
|
);
|
|
|
|
final _RecordingRelaySessionNotifier relay;
|
|
final NostrFilter filter;
|
|
final void Function(NostrEvent) onEvent;
|
|
final void Function(String message)? onClosed;
|
|
final void Function(RelaySubscriptionStatus) onStatusChanged;
|
|
final opened = Completer<void Function()>();
|
|
bool live = true;
|
|
|
|
void _remove() {
|
|
live = false;
|
|
relay.filters.remove(filter);
|
|
relay.subscriptions.remove(this);
|
|
}
|
|
|
|
/// The open future resolves (EOSE, retryable CLOSED or the 500 ms timeout).
|
|
void open() => opened.complete(_remove);
|
|
void ready() => onStatusChanged(RelaySubscriptionStatus.ready);
|
|
|
|
/// A retryable CLOSED: the open future resolves, then status is retrying.
|
|
void retrying() {
|
|
if (!opened.isCompleted) open();
|
|
onStatusChanged(RelaySubscriptionStatus.retrying);
|
|
}
|
|
|
|
/// A terminal CLOSED on a subscription that is already open.
|
|
void closeTerminal() {
|
|
_remove();
|
|
onClosed?.call('blocked: test');
|
|
}
|
|
|
|
/// A terminal CLOSED before the open future resolves.
|
|
void fail() {
|
|
_remove();
|
|
onClosed?.call('blocked: test');
|
|
opened.completeError(Exception('blocked: test'));
|
|
}
|
|
}
|
|
|
|
class _FakeAppLifecycleNotifier extends AppLifecycleNotifier {
|
|
@override
|
|
AppLifecycleState build() => AppLifecycleState.resumed;
|
|
}
|