perf(mobile): read only changed custom emoji sets on reconnect (#9446)

Once anything has read the custom emoji palette (opening any channel
does), every reconnect refetches every member's kind 30030 emoji set. On
Block's Builderlab that is 123 sets, about 1 MB, on every resume, though
the sets rarely change. The provider also watched the whole session
state, not just its status.

The palette now keeps the sets it has read per author and, on a
reconnect, asks only for sets written since shortly before the previous
read (`since` reaching back `relayCrossDeviceSkewSeconds`, the window
the unread catch-up already uses for events other devices write). A
newer set replaces the known one for its author, with the relay's order
for a same-second tie (the lower event id wins); the palette is the
union as before, recomputed only when a set changes, so a reconnect that
brings nothing new republishes the identical list and rebuilds nothing.
A community or account switch (a new relay client) starts over with a
full read.

Two side benefits: the loaded palette stays visible while disconnected
(before, it was empty until the full read finished, so `:shortcode:`s in
visible messages briefly showed as text on resume), and the palette no
longer refetches on every reconnect attempt during backoff, only on
status changes.

### Validation

Added test: the first read has no `since`; a reconnect with nothing new
sends a `since` and keeps the palette as the identical list; a new
member's set and a replaced set both arrive in the window and update it;
a same-second replacement wins with a lower id and is ignored with a
higher one. It fails without this change. Existing emoji picker tests
pass; full mobile test suite and `flutter analyze` pass.

On an iPhone 12 mini signed in to Block's Builderlab (instrumented
profile build): after opening a channel, a resume after 60 s in the
background downloaded the 1 MB of sets again (kind 30030, 123 events).
With this change the same resume sent the read with a `since` and got no
events back, so the 1 MB was not downloaded again; the first read when
opening the channel is unchanged (123 sets, 1 MB).

### Regressions

A set removed with a NIP-09 deletion (rather than replaced) stays in the
palette until the app restarts, since a deletion isn't a newer set. Buzz
clients edit a set by replacing it (desktop removes a shortcode by
republishing the set), so that only affects other clients, and desktop's
emoji directory keeps deleted sets the same way. A set written by a
device whose clock is more than 30 minutes behind is missed until
restart, the same bound the unread catch-up accepts.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
Tom Brow
2026-11-13 13:40:32 -08:00
committed by GitHub
parent 237a39fe76
commit 9fc2b33320
2 changed files with 173 additions and 10 deletions

View File

@@ -1,5 +1,6 @@
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../read_state/read_state_time.dart';
import '../relay/relay.dart';
import 'custom_emoji.dart';
@@ -7,39 +8,85 @@ import 'custom_emoji.dart';
///
/// On build, fetches every member's set and collapses to one entry per
/// shortcode (see [unionCustomEmoji]). Re-fetches when the relay session
/// reconnects. The palette is the single source of truth consumed by the
/// renderer, picker, autocomplete, and reaction/send tag plumbing.
/// reconnects, asking only for sets written since shortly before the previous
/// read: the sets are a megabyte on a busy community and rarely change. The
/// palette is the single source of truth consumed by the renderer, picker,
/// autocomplete, and reaction/send tag plumbing.
class CustomEmojiPaletteNotifier extends AsyncNotifier<List<CustomEmoji>> {
RelayClient? _client;
/// The latest set read per author, for this [_client].
final Map<String, NostrEvent> _sets = {};
/// When the last complete read was sent.
int? _readAt;
/// [unionCustomEmoji] of [_sets], recomputed only when a set changes so an
/// unchanged palette keeps its identity and rebuilds no listeners.
List<CustomEmoji> _palette = const [];
@override
Future<List<CustomEmoji>> build() {
ref.watch(relayClientProvider);
ref.watch(relaySessionProvider);
final client = ref.watch(relayClientProvider);
ref.watch(relaySessionProvider.select((state) => state.status));
if (!identical(client, _client)) {
_client = client;
_sets.clear();
_readAt = null;
_palette = const [];
}
return _fetch();
}
Future<List<CustomEmoji>> _fetch() async {
final sessionState = ref.read(relaySessionProvider);
if (sessionState.status != SessionStatus.connected) return [];
if (sessionState.status != SessionStatus.connected) return _palette;
final client = _client;
final previousRead = _readAt;
final sentAt = currentUnixSeconds();
try {
final session = ref.read(relaySessionProvider.notifier);
final events = await session.fetchHistory(
const NostrFilter(
kinds: [kindEmojiSet],
tags: {
NostrFilter(
kinds: const [kindEmojiSet],
tags: const {
'#d': [customEmojiSetDTag],
},
// Another device can store a set backdated up to this far, so a
// repeated read reaches back past the previous one.
since: previousRead == null
? null
: previousRead - relayCrossDeviceSkewSeconds,
// One 30030 per member; the relay keeps only the latest per
// (pubkey, d_tag), so this bounds member count, not history.
limit: 500,
),
);
return unionCustomEmoji(events);
if (identical(client, _client)) {
var changed = false;
for (final event in events) {
final known = _sets[event.pubkey];
if (known == null || _replaces(event, known)) {
_sets[event.pubkey] = event;
changed = true;
}
}
if (changed) _palette = unionCustomEmoji(_sets.values);
_readAt = sentAt;
}
return _palette;
} catch (_) {
return [];
return _palette;
}
}
/// The relay's replaceable-event order: the newer set wins, and on a
/// same-second tie the lower id does.
static bool _replaces(NostrEvent event, NostrEvent known) =>
event.createdAt > known.createdAt ||
(event.createdAt == known.createdAt && event.id.compareTo(known.id) < 0);
/// Force a re-fetch of the community palette.
Future<void> refresh() async {
state = const AsyncValue.loading();

View File

@@ -0,0 +1,116 @@
import 'package:buzz/shared/custom_emoji/custom_emoji.dart';
import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() {
test('a reconnect reads only sets written since the previous read', () async {
final relay = _EmojiRelay()
..sets['alice'] = _set('alice', 1000, {'a': 'https://e/a.png'});
final container = ProviderContainer(
overrides: [
relaySessionProvider.overrideWith(() => relay),
relayClientProvider.overrideWithValue(
RelayClient(baseUrl: 'http://localhost:3000'),
),
],
);
addTearDown(container.dispose);
container.listen(customEmojiPaletteProvider, (_, _) {});
Future<List<String>> palette() async => [
for (final emoji in await container.read(
customEmojiPaletteProvider.future,
))
emoji.shortcode,
];
Future<void> reconnect() async {
relay.setStatus(SessionStatus.disconnected);
await container.read(customEmojiPaletteProvider.future);
relay.setStatus(SessionStatus.connected);
}
expect(await palette(), ['a']);
expect(relay.since, [null]);
// Nothing new: the reconnect reads a short window, and the known sets stay.
await reconnect();
expect(await palette(), ['a']);
expect(relay.since, hasLength(2));
expect(relay.since.last, isNotNull);
// A new member's set and a replaced set both arrive in that window.
relay.sets['bob'] = _set('bob', relay.since.last! + 10, {
'b': 'https://e/b.png',
});
relay.sets['alice'] = _set('alice', relay.since.last! + 20, {
'c': 'https://e/c.png',
});
await reconnect();
expect(await palette(), ['b', 'c']);
// Nothing new again: the reconnect publishes the identical list.
final unchanged = await container.read(customEmojiPaletteProvider.future);
await reconnect();
expect(
await container.read(customEmojiPaletteProvider.future),
same(unchanged),
);
// On a same-second tie the relay keeps the lower id, and so does the
// palette.
final second = relay.sets['alice']!.createdAt;
relay.sets['alice'] = _set('alice', second, {
'd': 'https://e/d.png',
}, id: '0');
await reconnect();
expect(await palette(), ['b', 'd']);
relay.sets['alice'] = _set('alice', second, {
'e': 'https://e/e.png',
}, id: 'z');
await reconnect();
expect(await palette(), ['b', 'd']);
});
}
NostrEvent _set(
String pubkey,
int createdAt,
Map<String, String> emoji, {
String? id,
}) => NostrEvent(
id: id ?? '$pubkey$createdAt',
pubkey: pubkey,
createdAt: createdAt,
kind: kindEmojiSet,
tags: [
['d', customEmojiSetDTag],
for (final MapEntry(:key, :value) in emoji.entries) ['emoji', key, value],
],
content: '',
sig: '',
);
class _EmojiRelay extends RelaySessionNotifier {
final Map<String, NostrEvent> sets = {};
final List<int?> since = [];
@override
SessionState build() => const SessionState(status: SessionStatus.connected);
void setStatus(SessionStatus status) => state = SessionState(status: status);
@override
Future<List<NostrEvent>> fetchHistory(
NostrFilter filter, {
Duration timeout = const Duration(seconds: 8),
}) async {
expect(filter.kinds, [kindEmojiSet]);
since.add(filter.since);
return [
for (final event in sets.values)
if (event.createdAt >= (filter.since ?? 0)) event,
];
}
}