mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +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>
491 lines
17 KiB
Dart
491 lines
17 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:clock/clock.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
|
|
import '../../shared/agents/remote_agents.dart';
|
|
import '../../shared/agents/owned_agent_directory.dart';
|
|
import '../../shared/relay/relay.dart';
|
|
|
|
/// Community-scoped presence: absent means unknown. Polls recover expired leases.
|
|
///
|
|
/// Presence is a best-effort estimate between foreground polls. Per-key
|
|
/// revisions fence stale query completions. Snapshot/live ordering is not
|
|
/// causal: snapshots carry relay time and live events carry signer time. A
|
|
/// live event at/below the relay snapshot second is confirmed by a fresh
|
|
/// snapshot (persistence precedes fan-out). An empty snapshot has no relay
|
|
/// second, so a delayed older live event can briefly supersede its Offline;
|
|
/// the next 60-second poll corrects it.
|
|
class PresenceCacheNotifier extends Notifier<Map<String, String>> {
|
|
/// Bound deduplication memory; redelivery must not re-arm confirmation.
|
|
static const _seenIdLimit = 256;
|
|
|
|
/// How long a key nobody shows stays followed, so scrolling back and forth
|
|
/// doesn't reopen the subscription on every row.
|
|
static const releaseDelay = Duration(seconds: 30);
|
|
|
|
final Set<String> _tracked = {};
|
|
// Widgets currently showing each key. A key with none is released, then
|
|
// retired once it has been released for [releaseDelay] unless shown again.
|
|
final Map<String, int> _holders = {};
|
|
// When each released key was released.
|
|
final Map<String, DateTime> _released = {};
|
|
Timer? _retire;
|
|
final Set<String> _pending = {};
|
|
final Map<String, int> _revisions = {};
|
|
final Map<String, int> _timestamps = {};
|
|
final Map<String, int> _snapshotAt = {};
|
|
final List<String> _seenIds = [];
|
|
// Keys the live subscription asks for. Only tracked keys are subscribed:
|
|
// a community's presence heartbeats arrive many times a second.
|
|
final Set<String> _subscribedKeys = {};
|
|
void Function()? _presenceUnsub;
|
|
// Drops the replacement being opened, until it is promoted or abandoned.
|
|
void Function()? _abandonPending;
|
|
Timer? _poll;
|
|
Timer? _queued;
|
|
Timer? _resubscribe;
|
|
int _nextSubscription = 0;
|
|
int _activeSubscription = 0;
|
|
bool _subscribeAttempted = false;
|
|
int _generation = 0;
|
|
int _epoch = 0;
|
|
bool _querying = false;
|
|
bool _opening = false;
|
|
bool _retrying = false;
|
|
(String, String?)? _scope;
|
|
|
|
@override
|
|
Map<String, String> build() {
|
|
final sessionState = ref.watch(relaySessionProvider);
|
|
final foreground = ref.watch(appForegroundProvider);
|
|
final scope = ref.watch(
|
|
relayConfigProvider.select((config) => (config.baseUrl, config.nsec)),
|
|
);
|
|
_retire?.cancel();
|
|
_retire = null;
|
|
_tracked.removeAll(_released.keys);
|
|
_released.clear();
|
|
// A new community keeps only the keys still on screen.
|
|
if (_scope != scope) {
|
|
_tracked
|
|
..clear()
|
|
..addAll(_holders.keys);
|
|
}
|
|
_scope = scope;
|
|
final generation = ++_generation;
|
|
_epoch++;
|
|
_querying = _opening = _retrying = false;
|
|
_revisions.clear();
|
|
_timestamps.clear();
|
|
_snapshotAt.clear();
|
|
_seenIds.clear();
|
|
_subscribedKeys.clear();
|
|
_activeSubscription = 0;
|
|
_subscribeAttempted = false;
|
|
_pending
|
|
..clear()
|
|
..addAll(_tracked);
|
|
ref.onDispose(() {
|
|
_generation++;
|
|
_presenceUnsub?.call();
|
|
_presenceUnsub = null;
|
|
_abandonPending?.call();
|
|
_abandonPending = null;
|
|
_poll?.cancel();
|
|
_queued?.cancel();
|
|
_queued = null;
|
|
_resubscribe?.cancel();
|
|
_resubscribe = null;
|
|
_retire?.cancel();
|
|
_retire = null;
|
|
});
|
|
if (sessionState.status == SessionStatus.connected && foreground) {
|
|
_poll = Timer.periodic(const Duration(seconds: 60), (_) {
|
|
// A replacement the relay never answered must not hold the slot, so a
|
|
// lost REQ costs at most one poll interval.
|
|
_abandonPending?.call();
|
|
if (_presenceUnsub == null || !_covered) {
|
|
unawaited(_subscribe(generation));
|
|
}
|
|
// The snapshot backstop runs for a live stream even while a widening
|
|
// keeps failing, so expired leases are still corrected.
|
|
if (_presenceUnsub != null && !_querying) {
|
|
_pending.addAll(_tracked);
|
|
_schedule(generation);
|
|
}
|
|
});
|
|
// A transport may report ready synchronously; initialize state first.
|
|
Future.microtask(() => _subscribe(generation));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
/// Follow presence for exact keys while they are shown. Call the returned
|
|
/// function once when they no longer are.
|
|
void Function() track(List<String> pubkeys) {
|
|
final keys = {for (final key in pubkeys) key.trim().toLowerCase()}
|
|
..remove('');
|
|
var added = false;
|
|
for (final key in keys) {
|
|
_holders[key] = (_holders[key] ?? 0) + 1;
|
|
_released.remove(key);
|
|
if (_tracked.add(key)) {
|
|
_pending.add(key);
|
|
added = true;
|
|
}
|
|
}
|
|
// While live (the poll runs only then), a new key needs a subscription
|
|
// that covers it. A snapshot read before that one opens can miss a change,
|
|
// so the key is read again once it is covered.
|
|
if (added && (_poll?.isActive ?? false)) {
|
|
_queueResubscribe(_generation);
|
|
} else {
|
|
_schedule(_generation);
|
|
}
|
|
var released = false;
|
|
return () {
|
|
if (released) return;
|
|
released = true;
|
|
for (final key in keys) {
|
|
final holders = (_holders[key] ?? 0) - 1;
|
|
if (holders > 0) {
|
|
_holders[key] = holders;
|
|
} else {
|
|
_holders.remove(key);
|
|
_released[key] = clock.now();
|
|
}
|
|
}
|
|
if (_released.isNotEmpty && ref.mounted) {
|
|
_retire ??= Timer(releaseDelay, _retireReleased);
|
|
}
|
|
};
|
|
}
|
|
|
|
/// Stops following keys released at least [releaseDelay] ago, and narrows
|
|
/// the live subscription to what is still shown. Later releases wait for
|
|
/// the next sweep, so the subscription narrows at most once per delay.
|
|
void _retireReleased() {
|
|
_retire = null;
|
|
if (!ref.mounted) return;
|
|
final cutoff = clock.now().subtract(releaseDelay);
|
|
final retired = {
|
|
for (final entry in _released.entries)
|
|
if (!entry.value.isAfter(cutoff)) entry.key,
|
|
};
|
|
_released.removeWhere((key, _) => retired.contains(key));
|
|
if (_released.isNotEmpty) _retire = Timer(releaseDelay, _retireReleased);
|
|
if (retired.isEmpty) return;
|
|
_tracked.removeAll(retired);
|
|
_pending.removeAll(retired);
|
|
for (final key in retired) {
|
|
_timestamps.remove(key);
|
|
_snapshotAt.remove(key);
|
|
// A read from this lifetime must not fill the next one.
|
|
_revisions[key] = (_revisions[key] ?? 0) + 1;
|
|
}
|
|
// Absent means unknown: nothing keeps a retired key current.
|
|
final kept = {
|
|
for (final entry in state.entries)
|
|
if (!retired.contains(entry.key)) entry.key: entry.value,
|
|
};
|
|
if (kept.length != state.length) state = kept;
|
|
if (_poll?.isActive ?? false) _queueResubscribe(_generation);
|
|
}
|
|
|
|
bool get _covered => setEquals(_subscribedKeys, _tracked);
|
|
|
|
void _queueResubscribe(int generation) {
|
|
_resubscribe ??= Timer(Duration.zero, () {
|
|
_resubscribe = null;
|
|
// Without a subscription, the next poll opens one with every key.
|
|
if (generation == _generation &&
|
|
(_presenceUnsub != null || !_subscribeAttempted)) {
|
|
unawaited(_subscribe(generation));
|
|
}
|
|
});
|
|
}
|
|
|
|
void _schedule(int generation) {
|
|
_queued ??= Timer(Duration.zero, () {
|
|
_queued = null;
|
|
if (generation == _generation && _presenceUnsub != null && !_retrying) {
|
|
unawaited(_refresh(generation));
|
|
}
|
|
});
|
|
}
|
|
|
|
void _invalidateSnapshot() {
|
|
_epoch++;
|
|
_querying = false;
|
|
_pending.addAll(_tracked);
|
|
if (state.isNotEmpty) state = {};
|
|
}
|
|
|
|
Future<void> _subscribe(int generation) async {
|
|
if (_opening || generation != _generation) return;
|
|
if (_tracked.isEmpty) {
|
|
// Nobody is shown: close the stream, and the next track opens one.
|
|
_presenceUnsub?.call();
|
|
_presenceUnsub = null;
|
|
_subscribedKeys.clear();
|
|
_subscribeAttempted = _retrying = false;
|
|
return;
|
|
}
|
|
if (_presenceUnsub != null && _covered) return;
|
|
// One subscription opens at a time. A replacement holds this until it is
|
|
// promoted or abandoned, so tracking bursts widen it in later rounds.
|
|
_opening = true;
|
|
_subscribeAttempted = true;
|
|
final keys = _tracked.toList()..sort();
|
|
final subscription = ++_nextSubscription;
|
|
// A replacement becomes active only on its own first ready: returning from
|
|
// subscribeWithStatus also happens on a retryable CLOSED or a timeout.
|
|
// Until then the active subscription and the cache stay as they are.
|
|
final replacing = _presenceUnsub != null;
|
|
var pending = replacing;
|
|
var closed = false;
|
|
// Status the first subscription reports before it becomes active.
|
|
var retrying = false;
|
|
void Function()? unsub;
|
|
void close() {
|
|
if (closed) return;
|
|
closed = true;
|
|
unsub?.call(); // otherwise released when subscribeWithStatus returns
|
|
}
|
|
|
|
bool current() =>
|
|
generation == _generation &&
|
|
!closed &&
|
|
subscription == _activeSubscription;
|
|
void promote() {
|
|
pending = false;
|
|
_abandonPending = null;
|
|
_opening = false;
|
|
final previous = _presenceUnsub;
|
|
final added = keys.where(
|
|
(key) => _tracked.contains(key) && !_subscribedKeys.contains(key),
|
|
);
|
|
_pending.addAll(added);
|
|
_activeSubscription = subscription;
|
|
_retrying = retrying;
|
|
_presenceUnsub = close;
|
|
_subscribedKeys
|
|
..clear()
|
|
..addAll(keys);
|
|
previous?.call();
|
|
// Still backing off: its ready reads everything once it is live.
|
|
if (_retrying) {
|
|
_invalidateSnapshot();
|
|
return;
|
|
}
|
|
// Keys tracked or retired while this one opened need another one.
|
|
if (!_covered) _queueResubscribe(generation);
|
|
// Newly covered keys are read only now, so no change between an earlier
|
|
// snapshot and their live coverage is lost.
|
|
_schedule(generation);
|
|
}
|
|
|
|
void abandon() {
|
|
pending = false;
|
|
_abandonPending = null;
|
|
close();
|
|
if (generation != _generation) return;
|
|
_opening = false;
|
|
// Keys only it would cover get a snapshot; the poll retries the widening.
|
|
_schedule(generation);
|
|
}
|
|
|
|
if (pending) _abandonPending = abandon;
|
|
try {
|
|
unsub = await ref
|
|
.read(relaySessionProvider.notifier)
|
|
.subscribeWithStatus(
|
|
NostrFilter(
|
|
kinds: const [EventKind.presenceUpdate],
|
|
authors: keys,
|
|
limit: 0,
|
|
),
|
|
(event) {
|
|
if (current() && !_retrying) _handlePresenceEvent(event);
|
|
},
|
|
onStatusChanged: (status) {
|
|
if (generation != _generation || closed) return;
|
|
if (pending) {
|
|
status == RelaySubscriptionStatus.ready ? promote() : abandon();
|
|
return;
|
|
}
|
|
if (subscription != _activeSubscription) {
|
|
retrying = status == RelaySubscriptionStatus.retrying;
|
|
return;
|
|
}
|
|
_retrying = status == RelaySubscriptionStatus.retrying;
|
|
_invalidateSnapshot();
|
|
if (_retrying) return;
|
|
// Keys tracked or retired during the backoff need another one.
|
|
if (!_covered) {
|
|
_queueResubscribe(generation);
|
|
}
|
|
_schedule(generation);
|
|
},
|
|
onClosed: (_) {
|
|
if (generation != _generation || closed) return;
|
|
if (pending) {
|
|
abandon();
|
|
return;
|
|
}
|
|
closed = true;
|
|
if (subscription != _activeSubscription) return;
|
|
_presenceUnsub = null;
|
|
_subscribedKeys.clear();
|
|
_invalidateSnapshot();
|
|
},
|
|
);
|
|
if (generation != _generation || closed) {
|
|
unsub();
|
|
return;
|
|
}
|
|
// With nothing to protect, the first subscription is active once open.
|
|
if (!replacing) promote();
|
|
} catch (error) {
|
|
if (generation != _generation) return;
|
|
debugPrint('[PresenceCacheNotifier] subscription failed: $error');
|
|
if (replacing) {
|
|
if (pending) abandon();
|
|
} else if (subscription != _activeSubscription) {
|
|
_opening = false;
|
|
_invalidateSnapshot();
|
|
}
|
|
}
|
|
}
|
|
|
|
void _handlePresenceEvent(NostrEvent event) {
|
|
final pubkey = event.pubkey.toLowerCase();
|
|
final status = event.content.trim();
|
|
if (event.kind != EventKind.presenceUpdate ||
|
|
!_tracked.contains(pubkey) ||
|
|
!_validStatus(status) ||
|
|
event.createdAt < (_timestamps[pubkey] ?? 0) ||
|
|
_seenRecently(event.id)) {
|
|
return;
|
|
}
|
|
// Accepted evidence fences in-flight queries, even if it needs confirmation.
|
|
_revisions[pubkey] = (_revisions[pubkey] ?? 0) + 1;
|
|
// Equality cannot order events within the relay's observation second.
|
|
if (event.createdAt <= (_snapshotAt[pubkey] ?? 0)) {
|
|
_pending.add(pubkey);
|
|
_schedule(_generation);
|
|
return;
|
|
}
|
|
_timestamps[pubkey] = event.createdAt;
|
|
if (state[pubkey] != status) state = {...state, pubkey: status};
|
|
}
|
|
|
|
Future<void> _refresh(int generation) async {
|
|
if (_querying || _pending.isEmpty) return;
|
|
_querying = true;
|
|
final epoch = _epoch;
|
|
final session = ref.read(relaySessionProvider.notifier);
|
|
while (_pending.isNotEmpty) {
|
|
final keys = _pending.take(100).toList();
|
|
_pending.removeAll(keys);
|
|
final revisions = {for (final key in keys) key: _revisions[key] ?? 0};
|
|
List<NostrEvent>? events;
|
|
try {
|
|
events = await session.queryRelay([
|
|
NostrFilter(
|
|
kinds: [EventKind.presenceUpdate],
|
|
authors: keys,
|
|
limit: keys.length,
|
|
),
|
|
]);
|
|
} catch (error) {
|
|
debugPrint('[PresenceCacheNotifier] snapshot failed: $error');
|
|
}
|
|
if (generation != _generation || epoch != _epoch) return;
|
|
final latest = <String, NostrEvent>{};
|
|
var observedAt = 0;
|
|
for (final event in events ?? <NostrEvent>[]) {
|
|
final key = (event.getTagValue('p') ?? event.pubkey).toLowerCase();
|
|
if (!revisions.containsKey(key) ||
|
|
event.kind != EventKind.presenceUpdate ||
|
|
!_validStatus(event.content.trim())) {
|
|
continue;
|
|
}
|
|
if (!latest.containsKey(key) ||
|
|
event.createdAt > latest[key]!.createdAt) {
|
|
latest[key] = event;
|
|
}
|
|
if (event.createdAt > observedAt) observedAt = event.createdAt;
|
|
}
|
|
final updated = {...state};
|
|
for (final key in keys) {
|
|
// A key retired meanwhile stays absent.
|
|
if (!_tracked.contains(key) ||
|
|
(_revisions[key] ?? 0) != revisions[key]) {
|
|
continue;
|
|
}
|
|
if (events == null) {
|
|
updated.remove(key); // failure is unknown; next poll retries
|
|
} else {
|
|
// Shared synthesis clock fences the batch; empty answers retain it.
|
|
if (observedAt > (_snapshotAt[key] ?? 0)) {
|
|
_snapshotAt[key] = observedAt;
|
|
}
|
|
updated[key] = latest[key]?.content.trim() ?? 'offline';
|
|
}
|
|
}
|
|
if (!mapEquals(state, updated)) state = updated;
|
|
}
|
|
_querying = false;
|
|
}
|
|
|
|
bool _seenRecently(String id) {
|
|
if (id.isEmpty) return false;
|
|
if (_seenIds.contains(id)) return true;
|
|
_seenIds.add(id);
|
|
if (_seenIds.length > _seenIdLimit) _seenIds.removeAt(0);
|
|
return false;
|
|
}
|
|
|
|
bool _validStatus(String status) =>
|
|
status == 'online' || status == 'away' || status == 'offline';
|
|
}
|
|
|
|
final presenceCacheProvider =
|
|
NotifierProvider<PresenceCacheNotifier, Map<String, String>>(
|
|
PresenceCacheNotifier.new,
|
|
);
|
|
|
|
/// Presentation shared by profiles, DMs and mentions. Remote agents wake on
|
|
/// messages. Their verified Builderlab runtime registration is enough to show
|
|
/// Online when the account API is unavailable or signed out, unless the owner
|
|
/// has a saved registry snapshot that excludes it. The registry also supports
|
|
/// older agents without runtime metadata. Local presence is unchanged.
|
|
final presentedPresenceProvider = Provider<Map<String, String>>((ref) {
|
|
final presence = ref.watch(presenceCacheProvider);
|
|
final directoryState = ref.watch(ownedAgentDirectoryProvider);
|
|
final directory = directoryState.isLoading || directoryState.hasError
|
|
? null
|
|
: directoryState.asData?.value;
|
|
final controller = ref.watch(remoteAgentControllerProvider);
|
|
void changed() => ref.invalidateSelf();
|
|
controller.addListener(changed);
|
|
ref.onDispose(() => controller.removeListener(changed));
|
|
final saved = ref.watch(savedRemoteAvailabilityProvider);
|
|
final remote = {
|
|
...?ref.watch(availableRemoteAgentsProvider).value,
|
|
if (!controller.registryLoaded &&
|
|
!saved.isLoading &&
|
|
!saved.hasError &&
|
|
saved.hasValue)
|
|
for (final agent in directory ?? <OwnedAgentDirectoryEntry>[])
|
|
if (agent.runtime == 'block.builderlab/builderlab' &&
|
|
(saved.value == null || saved.value!.contains(agent.pubkey)))
|
|
agent.pubkey,
|
|
}..removeAll(controller.deletedAgents);
|
|
if (remote.isEmpty) return presence;
|
|
return {...presence, for (final pubkey in remote) pubkey: 'online'};
|
|
});
|