Files
buzz/mobile/lib/features/search/search_provider.dart
Tom Brow 1a5c6939c5 perf(mobile): save the open-channel directory and catch it up (#9513)
Search and invite recovery read a community's open-channel directory
(every open, listed channel's kind 39000 metadata) from the relay, and
match names on the device. Until now the app kept that directory in
memory for 30 seconds only, so every search session after that, and the
first search after every launch, downloaded the whole directory again.
This follows [#9466 directory-only search
load](https://github.com/block/buzz/pull/9466) and [#9457 directory
keeps message times](https://github.com/block/buzz/pull/9457), which
made each of those downloads cheaper; this one makes most of them
unnecessary.

Now the directory is saved in a file per community and account, next to
the image cache, and search reads it from there:

- **What's saved.** Only the latest revision of each open, listed,
non-DM channel. The relay's directory read also returns the user's own
private, unlisted and DM channels; those are never held or saved as the
directory, and a channel whose latest revision is no longer discoverable
drops out.
- **First read.** The first time search opens, the app downloads the
whole directory, as before, and saves it.
- **Catch-up.** When search opens later, it shows the saved copy at
once. At most once a minute, it asks the relay in the background only
for directory changes since the newest saved one, or since the last read
started by the device clock if that is earlier (less a minute of
overlap), and merges them in. The relay can stamp a busy channel's
metadata minutes ahead of wall time, so the newest saved stamp alone
could skip channels created meanwhile. A catch-up that brings back
nothing new saves nothing and leaves the list alone, and a search opened
while a background read is still running shares it rather than starting
another.
- **Offline open.** A search opened before the session connects shows
the saved copy and runs its check on the next connect.
- **Daily full read.** Once the last full read is a day old (or dated in
the future, by a clock since set back), the next check downloads the
whole directory in the background and replaces the saved copy, which
drops channels that became private or unlisted or were deleted. A
catch-up can't see those: the relay never serves them to a non-member.
- **Gone on open.** Opening a saved result that the relay no longer
serves (private or deleted) drops it from the directory at once, and no
directory read already in flight (background check, list refresh or
Retry) brings it back. A restore from disk never overrides a full read
already running, and a background read never displaces one.
- **Invite recovery** still downloads the whole directory, as on main:
it needs fresh memberships, and its read also refreshes the saved copy.
- **Cleanup.** Signing out of a community, replacing its account, or
leaving it deletes the file.

The saved events omit signatures (the relay signed them; the copy is a
cache of what it served). The file's JSON is encoded and decoded off the
UI isolate, and an unavailable caches directory (or one that takes over
3 seconds) just means no saved copy. A file that is unreadable, from
another version, or over 20,000 channels or 16 MiB is discarded and read
again from the relay. There is no relay change. `CONTEXT.md` gains an
"Open-channel directory" entry.

### Validation

| Workflow (small community, 63 open channels) | Directory bytes before
| Directory bytes after |
| --- | --- | --- |
| First search after install | 39.5 KB (2 requests) | 39.5 KB (2
requests) |
| Search again 2 minutes later | 39.5 KB (2 requests) | 0.6 KB (2
requests) |
| Relaunch, then search | 39.5 KB (2 requests) | 0.6 KB (2 requests) |

Measured on an iOS simulator signed in to a test community, with a
temporary local counter on each relay query response (not part of this
PR), main at
[6974237](69742376a9)
vs this branch. The full read grows with the number of open channels
(about 600 bytes each); the catch-up grows only with what changed.
Search results were identical on both builds, and opening an unjoined
result from the saved directory still showed its preview with Join.

Tests:

- A journey test drives the real channel list against a fake relay that
honors `since`, with a real file and a fake clock: the first reader
saves the directory without signatures; more readers within a minute ask
nothing; a minute later a reader asks only for changes since the newest
saved one less a minute; after a relaunch the saved copy serves at once
and the catch-up starts from it; a channel that turned private stays
until the daily full read replaces the copy; the search status never
shows loading for the background reads; a catch-up of only held events
leaves the list identical and the file unwritten; a second search a
minute into a slow full read shares it; and opening a channel the relay
no longer serves drops it, even with a read in flight. Each guard was
checked by breaking it: removing the once-a-minute limit, dropping
`since`, never doing the full read, merging the full read instead of
replacing, removing the drop-on-open, the no-change check, the shared
in-flight read, or the in-flight drop fence each fail the test.
- Focused cases against the same fake relay and real file, each checked
by breaking its guard: member-only private, unlisted and DM metadata is
never saved, and a saved channel that turns private drops out on
catch-up; a catch-up starts no later than the last read's start, across
a relaunch, so a channel created after a burst-stamped one is found; a
full read or check dated in the future by a clock set back is due; a
search opened before the session connects checks on connect; a restore
leaves a running full read's status alone and is not displaced by a
catch-up; a list or Retry full read in flight does not bring back a
channel dropped on open.
- Storage tests: the round trip omits signatures; unusable data is
discarded; a directory over the bounds leaves no stale copy; a closed
store neither reads nor writes; cleanup keeps only each community's
current account and its save in progress.
- The community test now also checks that replacing an account deletes
the old account's saved directory (fails without the cleanup call).
- Full mobile test suite and `flutter analyze` pass.

No visible change, so no screenshots: the same results appear, just
without a download on later searches.

### Regressions

- A channel that turns private or is deleted can still appear in search
for up to a day, until the daily full read, unless you open it (the
first open in a session asks the relay, drops it at once, and the relay
withholds its content). A channel already previewed earlier in the same
session reopens from its cached details without asking the relay, so it
stays until the daily read or a relaunch. Before, it disappeared from
the next search at least 30 seconds later.
- A channel that turns unlisted can also appear in search for up to a
day. Opening it does not drop it, and its content stays readable,
because the relay serves an unlisted open channel to anyone who names
it.
- A channel created while search is open appears the next time search
opens, not while it stays open. That was already the case within the
30-second window.
- The saved file costs some disk per community (about 30 KB for 63
channels, roughly 0.5 KB per channel), deleted on sign-out or leaving.

---------

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>
2026-11-15 12:31:58 -07:00

454 lines
15 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../../shared/relay/relay.dart';
import '../channels/channel.dart';
import '../channels/channel_management_provider.dart';
import '../channels/channels_provider.dart';
import 'name_match.dart';
@immutable
class SearchHit {
final String eventId;
final String content;
final int kind;
final String pubkey;
final String? channelId;
final String? channelName;
final int createdAt;
final double score;
final List<List<String>> tags;
const SearchHit({
required this.eventId,
required this.content,
required this.kind,
required this.pubkey,
this.channelId,
this.channelName,
required this.createdAt,
required this.score,
this.tags = const [],
});
factory SearchHit.fromJson(Map<String, dynamic> json) => SearchHit(
eventId: json['event_id'] as String,
content: json['content'] as String? ?? '',
kind: json['kind'] as int? ?? 9,
pubkey: json['pubkey'] as String,
channelId: json['channel_id'] as String?,
channelName: json['channel_name'] as String?,
createdAt: json['created_at'] as int? ?? 0,
score: (json['score'] as num?)?.toDouble() ?? 0.0,
tags:
(json['tags'] as List<dynamic>?)
?.map((t) => (t as List<dynamic>).map((e) => e as String).toList())
.toList() ??
const [],
);
}
@immutable
class SearchState {
final String query;
final List<SearchHit> messageResults;
final List<DirectoryUser> userResults;
final List<Channel> channelResults;
final bool isLoading;
final String? error;
/// The open-channel directory failed to load, so channel results may be
/// missing open channels the user has not joined.
final bool channelSearchFailed;
const SearchState({
this.query = '',
this.messageResults = const [],
this.userResults = const [],
this.channelResults = const [],
this.isLoading = false,
this.error,
this.channelSearchFailed = false,
});
const SearchState.initial()
: query = '',
messageResults = const [],
userResults = const [],
channelResults = const [],
isLoading = false,
error = null,
channelSearchFailed = false;
SearchState copyWith({
String? query,
List<SearchHit>? messageResults,
List<DirectoryUser>? userResults,
List<Channel>? channelResults,
bool? isLoading,
String? error,
bool? channelSearchFailed,
}) => SearchState(
query: query ?? this.query,
messageResults: messageResults ?? this.messageResults,
userResults: userResults ?? this.userResults,
channelResults: channelResults ?? this.channelResults,
isLoading: isLoading ?? this.isLoading,
error: error ?? this.error,
channelSearchFailed: channelSearchFailed ?? this.channelSearchFailed,
);
}
/// The channel name text a search [query] matches: lowercased, without a
/// leading "#".
String _channelNeedle(String query) =>
query.trim().toLowerCase().replaceFirst(RegExp(r'^#'), '');
/// Whether [query] searches open channels. A bare "#" does not, as on desktop.
bool _searchesOpenChannels(String query) => _channelNeedle(query).isNotEmpty;
/// Most channel rows one query shows, ranked best first.
const searchChannelResultLimit = 8;
/// Most people rows one query shows.
const searchPeopleShown = 8;
/// Ranks [channels] for a search [query] with the same rules as desktop
/// (buzz-app `SearchResults.tsx` and `store.ts` `searchPublic`): name match
/// rank first, an archived channel half a step behind a live one, then joined
/// channels in list order before open ones by name. A bare "#" lists joined
/// channels only, since desktop does not search open channels for it.
List<Channel> rankSearchChannels(Iterable<Channel> channels, String query) {
final needle = _channelNeedle(query);
final ranked = <({Channel channel, double rank, int order})>[];
for (final channel in channels) {
if (channel.isDm) continue;
// An archived channel stays findable only by its members.
final visible = channel.isArchived || needle.isEmpty
? channel.isMember
: channel.visibility == 'open' || channel.isMember;
if (!visible) continue;
final rank = matchRank(channel.name, needle);
if (rank == null) continue;
ranked.add((
channel: channel,
rank: rank + (channel.isArchived ? 0.5 : 0),
order: ranked.length,
));
}
ranked.sort((a, b) {
final byRank = a.rank.compareTo(b.rank);
if (byRank != 0) return byRank;
// Joined channels win ties and keep the list's order.
if (a.channel.isMember != b.channel.isMember) {
return a.channel.isMember ? -1 : 1;
}
if (a.channel.isMember) return a.order.compareTo(b.order);
final byName = a.channel.name.compareTo(b.channel.name);
return byName != 0 ? byName : a.channel.id.compareTo(b.channel.id);
});
return [
for (final entry in ranked.take(searchChannelResultLimit)) entry.channel,
];
}
class SearchNotifier extends Notifier<SearchState> {
Timer? _debounce;
// The relay lookups still running for the current query. The spinner shows
// only while one of them, or a directory load, is pending, so the last
// lookup to finish settles it regardless of which results came back empty.
bool _messagesPending = false;
bool _usersPending = false;
// The directory load this search started, until its future completes. The
// shared directory status is not enough: production marks it loading only
// after memberships arrive, and loaded before the new list is installed.
// A rebuild drops it, so a load from an earlier community cannot settle a
// newer one.
Object? _directoryLoad;
// This search has loaded, or tried to load, the directory. Until then an
// unloaded directory is not a failure to report.
bool _directoryAttempted = false;
// Bumped by every new query, clear and rebuild. A lookup writes its result
// only while its generation is current, so a late reply to an earlier query,
// even one with the same text, cannot settle the current spinner.
int _generation = 0;
@override
SearchState build() {
// Watch relayConfig so search state resets on a community or identity
// switch: myPubkeyProvider derives from its nsec.
ref.watch(relayConfigProvider);
_generation++;
_messagesPending = false;
_usersPending = false;
_directoryLoad = null;
_directoryAttempted = false;
// Channel rows are ranked once per query, so live channel events never
// reorder rows under a finger: they only update the shown rows' content.
// Rows are ranked again when the set of channels or their names change
// (the first load, a directory install, a rename); the directory status
// for this community also drives the spinner.
ref.listen(channelsProvider, (previous, next) {
final channels = next.asData?.value;
if (channels == null) return;
final before = previous?.asData?.value;
if (before == null || !_sameChannels(before, channels)) {
_refreshChannels();
} else {
_updateShownChannels(channels);
}
});
ref.listen(
channelDirectoryLoadStatusProvider,
(_, _) => _refreshChannels(),
);
// Offline, a directory load fails at once. Load it again on reconnect, so
// the failure clears without another query.
ref.listen(relaySessionProvider, (previous, next) {
if (next.status == SessionStatus.connected &&
previous?.status != SessionStatus.connected &&
_directoryFailed) {
retryChannels();
}
});
ref.onDispose(() {
_debounce?.cancel();
});
return const SearchState.initial();
}
void search(String query) {
_debounce?.cancel();
final trimmed = query.trim();
if (trimmed.isEmpty) {
clear();
return;
}
final generation = ++_generation;
// Pending from the keystroke, so a channel-list change during the
// debounce cannot show "No results" before the lookups start.
_messagesPending = true;
_usersPending = true;
state = SearchState(query: trimmed, isLoading: true);
_debounce = Timer(const Duration(milliseconds: 300), () {
_executeSearch(trimmed, generation);
});
}
void _executeSearch(String query, int generation) {
if (generation != _generation) return;
// Like desktop, a bare "#" lists joined channels without the directory.
if (_searchesOpenChannels(query)) _loadDirectory();
_refreshChannels();
_searchMessages(query, generation);
_searchUsers(query, generation);
}
bool get _isLoading =>
_messagesPending ||
_usersPending ||
(_searchesOpenChannels(state.query) &&
(_directoryLoad != null ||
_directoryStatus == ChannelDirectoryLoadStatus.loading));
/// This community's directory status, or null when the status describes
/// another community or no load has started.
ChannelDirectoryLoadStatus? get _directoryStatus {
final directory = ref.read(channelDirectoryLoadStatusProvider);
final scope = channelDirectoryScope(
ref.read(relayConfigProvider).baseUrl,
ref.read(myPubkeyProvider),
);
return directory.scope == scope ? directory.status : null;
}
/// Whether this community's directory is not loaded and no load for it is
/// running: it failed, or a newer channel refresh retired the load.
bool get _directoryMissing => switch (_directoryStatus) {
ChannelDirectoryLoadStatus.loaded ||
ChannelDirectoryLoadStatus.loading => false,
_ => true,
};
/// Whether this search loaded the directory for the current query and it
/// did not load. An earlier failure stays hidden while the next load runs.
bool get _directoryFailed =>
_searchesOpenChannels(state.query) &&
_directoryAttempted &&
_directoryLoad == null &&
_directoryMissing;
/// Loads the directory again after it failed, like desktop's Retry channels.
void retryChannels() {
_loadDirectory();
_refreshChannels();
}
/// Loads the open-channel directory so search also finds open channels the
/// user has not joined, as desktop search does.
void _loadDirectory() {
if (_directoryLoad != null) return;
final load = _directoryLoad = Object();
_directoryAttempted = true;
final channels = ref.read(channelsProvider.notifier);
Future<void> ensure() => channels.ensureDirectoryLoaded();
unawaited(
ensure()
.then((_) {
// A membership refresh that starts during the load retires it.
// Nothing failed, so the load ends with no status for this
// community, or idle. Load it again once; if that is retired
// too, search offers Retry instead of looping. A relay error
// ends in error and is not retried automatically.
if (!ref.mounted ||
_directoryLoad != load ||
!_directoryMissing ||
_directoryStatus == ChannelDirectoryLoadStatus.error) {
return null;
}
return ensure();
})
.catchError((Object error) {
debugPrint(
'[SearchNotifier] channel directory load failed: $error',
);
})
.whenComplete(() {
if (!ref.mounted || _directoryLoad != load) return;
_directoryLoad = null;
_refreshChannels();
}),
);
}
Future<void> _searchMessages(String query, int generation) async {
try {
final session = ref.read(relaySessionProvider.notifier);
final events = await session.fetchHistory(
NostrFilter(
kinds: const [9, 40002, 45001, 45003],
search: query,
limit: 20,
),
);
// Channel-name lookup from the cached channels list — not all hits
// will have a known channel (e.g. ones we're not a member of).
final channelsById = {
for (final c
in ref.read(channelsProvider).asData?.value ?? const <Channel>[])
c.id: c.name,
};
final hits = events
.map(
(e) => SearchHit(
eventId: e.id,
content: e.content,
kind: e.kind,
pubkey: e.pubkey,
channelId: e.channelId,
channelName: e.channelId != null
? channelsById[e.channelId!]
: null,
createdAt: e.createdAt,
score: 0.0,
tags: e.tags,
),
)
.toList();
if (!ref.mounted || generation != _generation) return;
_messagesPending = false;
state = state.copyWith(messageResults: hits, isLoading: _isLoading);
} catch (e) {
if (!ref.mounted || generation != _generation) return;
_messagesPending = false;
state = state.copyWith(isLoading: _isLoading, error: e.toString());
}
}
/// People asked of the directory search: more than [searchPeopleShown],
/// so archived people the page leaves out do not leave it short.
static const _peopleSearchLimit = 3 * searchPeopleShown;
Future<void> _searchUsers(String query, int generation) async {
List<DirectoryUser>? users;
try {
users = await ref
.read(channelActionsProvider)
.searchUsers(query, limit: _peopleSearchLimit);
} catch (_) {
// User search failure is non-critical — keep existing results.
}
if (!ref.mounted || generation != _generation) return;
_usersPending = false;
state = state.copyWith(userResults: users, isLoading: _isLoading);
}
/// Whether [a] and [b] hold the same channels under the same names, so a
/// query would match the same ones. A rename, as a directory check can
/// install, changes the matches.
static bool _sameChannels(List<Channel> a, List<Channel> b) {
if (a.length != b.length) return false;
final names = {for (final channel in a) channel.id: channel.name};
return b.every(
(channel) =>
names.containsKey(channel.id) && names[channel.id] == channel.name,
);
}
/// Shows each shown channel's latest content (membership, member count,
/// name) in the rows' existing order.
void _updateShownChannels(List<Channel> channels) {
final shown = state.channelResults;
if (shown.isEmpty) return;
final byId = {for (final channel in channels) channel.id: channel};
final updated = [for (final row in shown) byId[row.id] ?? row];
for (var i = 0; i < shown.length; i++) {
if (!identical(updated[i], shown[i])) {
state = state.copyWith(channelResults: updated);
return;
}
}
}
/// Publishes the channel rows and spinner for the current query.
void _refreshChannels() {
if (state.query.isEmpty) return;
state = state.copyWith(
// A reload keeps the previous community's list in AsyncLoading; only
// installed data belongs to this search's community.
channelResults: rankSearchChannels(
ref.read(channelsProvider).asData?.value ?? const <Channel>[],
state.query,
),
// The notice clears when another caller loads the directory.
channelSearchFailed: _directoryFailed,
isLoading: _isLoading,
);
}
void clear() {
_debounce?.cancel();
_generation++;
_messagesPending = false;
_usersPending = false;
state = const SearchState.initial();
}
}
final searchProvider = NotifierProvider<SearchNotifier, SearchState>(
SearchNotifier.new,
);