mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
## Summary While the app is open, a 60s timer reads the whole channel list again: every membership roster, the channel metadata, and the unread catch-up. On the test account that is **about 4MB of JSON every minute** on the 12 mini, about 240MB an hour, whether or not anything changed. The live subscriptions already deliver what the list is built from, so this PR removes the timer. The list is read again when a live event says it may have changed: - a relay notice that tags this reader: added to a channel or a new DM (kind 44100), removed from one (44101), or a DM hidden or shown on another device (30622) - a metadata edit on a listed channel (kind 9002, now part of the live filter) - a system notice on a listed channel that changes the channel itself: archived (including the relay auto-archiving an idle ephemeral channel), unarchived, deleted, visibility, topic, purpose, TTL and similar. Member joins and leaves don't count. The read starts 2s after the last such event, and no later than 10s after the first, so a burst costs one read. Reads start at least 10s apart however busy the relay is. A read that fails is retried with backoff (5s, doubling up to 5 minutes), including the read after a resume or reconnect. Nothing is read in the background: launch, resume, reconnect and pull to refresh read the list as before. Live subscriptions ask for no stored events (`limit: 0`), so nothing sent while one is down is replayed. So: - Each list read opens the notice subscription before it reads, and the read covers anything sent before. - If the relay closes the notice subscription or a channel chunk for a reason that may clear (busy, rate-limited, timed out), the relay session reopens it itself, as before. The channel list now hears about that through `subscribeWithStatus`. - If the relay refuses one as over its subscription limit, only that REQ is retried, after a jittered backoff (5s, doubling up to 5 minutes). The backoff starts over once a reopened subscription has stayed up for a minute. Any other refusal (`restricted:`, `invalid:` and so on) can't succeed unchanged, so it is left alone until the next connection, as on main. - A reopened subscription that is still up when its read comes due counts as a change, so the list is read once to catch up on what it missed. If the relay admits a REQ and then closes it again, it triggers no reads. Known gaps, accepted: deleting a channel or kicking a member sends this reader no notice, and archived channels have no live coverage, so an unarchive done on another device isn't seen. An edit to a newly added channel that lands in the round trip between reading its metadata and its live subscription starting is also missed. The list catches up on the next launch, resume, reconnect or pull to refresh. Archiving or unarchiving on this device re-reads the list at once, as before. ## Measurements iPhone 12 mini on Wi-Fi against the internal relay, app open and idle, instrumented profile build (HTTP response bodies after decompression, websocket text in). Measured on an earlier revision of this PR, which read on a 60s tick only after a change. Idle behavior is the same now (no change, no read). | 10 idle minutes | main | this PR | | --- | --- | --- | | Channel list reads | 10 | 1 | | HTTP queries | 40 | 5 | | HTTP response bytes | 39.9MB | 4.0MB | | Websocket bytes in | 4.4MB | 1.1MB | On main, every tick read memberships (348KB), another 310KB query and the unread catch-up (3.3MB). With this PR, the only read in the window came right after another device hid or showed a DM (kind 30622), which is exactly the kind of change it should pick up. Sizes are JSON after decompression; the relay gzips responses, so wire bytes are smaller (not measured). [#8901](https://github.com/block/buzz/pull/8901) separately shrinks each read's unread catch-up; the two are independent. ## Testing - New journey test: with the app open and nothing changing, nothing is read. Adding the reader to a channel, renaming a listed channel, archiving or auto-archiving one and removing the reader each cause one read about 2s later, and a member joining causes none. A change right after a read waits out the 10s gap. A steady stream of changes is read after 10s and then no more than every 10s. A burst costs one read. A failed read is retried with backoff and then stops. - New journey test, for the notice subscription and for a channel chunk: the relay refuses it twice as over its limit while the list changes. It is retried with backoff, and once it has stayed up the list is read once to catch up. Later the relay drops it, and having stayed up it is reopened within about 5s and catches up again. Then it delivers live. The relay then closes it as busy while the list changes, and the list catches up once it is back; closed again right after reopening, it triggers no read until it stays up. Refused as `restricted:`, it is not retried. - The resume journey: a reconnect read and a resume read each fail once while a channel is added, and each is retried and shows the channel. - Each guard was removed once to confirm a test fails: the debounce, the max wait, the minimum gap, the read retry (including after reconnect and resume), the catch-up reads after a retry or a relay-session reopen, the still-up checks, the backoff restart, the background check, retrying only capacity refusals, and clearing refusals on a new connection. - The terminal-rejection tests expect a chunk refused as `restricted:` never to be retried on that connection or to cause a list or history read, and a new connection to retry it at once. - `just mobile-check` and `just mobile-test` pass. - Device: on the 12 mini, 10 idle minutes with the app open, before and after (table above). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
166 lines
6.0 KiB
Dart
166 lines
6.0 KiB
Dart
part of 'channels_provider.dart';
|
|
|
|
/// Relay-signed notices that tag this reader when its channel list changes:
|
|
/// it was added to a channel (including a new DM) or removed from one, or one
|
|
/// of its DMs was hidden or shown on another device.
|
|
const _channelListNoticeKinds = [
|
|
EventKind.memberAddedNotification,
|
|
EventKind.memberRemovedNotification,
|
|
EventKind.dmVisibility,
|
|
];
|
|
|
|
/// System notices (kind:40099) on a listed channel that change the channel
|
|
/// itself rather than its messages or members.
|
|
const _channelChangeSystemTypes = {
|
|
'auto_join_changed',
|
|
'channel_archived',
|
|
'channel_auto_archived',
|
|
'channel_deleted',
|
|
'channel_unarchived',
|
|
'join_role_changed',
|
|
'purpose_changed',
|
|
'topic_changed',
|
|
'ttl_changed',
|
|
'unlisted_changed',
|
|
'visibility_changed',
|
|
};
|
|
|
|
/// Tracks whether the channel list may have changed since it was last read.
|
|
///
|
|
/// The list is read on every launch, resume, reconnect and pull to refresh.
|
|
/// Between those, live events say when it changed: a notice for this reader,
|
|
/// or a metadata edit or system notice on a listed channel. Each one schedules
|
|
/// a read (see [_ChannelsNotifierLiveSubscriptions._noteListChanged]).
|
|
///
|
|
/// The live subscriptions ask for no stored events (`limit: 0`), so nothing
|
|
/// sent while one is down is replayed. Each list read therefore opens the
|
|
/// notice subscription before it reads, and reopening a subscription between
|
|
/// reads schedules a read to catch up on what it missed.
|
|
extension _ChannelListChanges on ChannelsNotifier {
|
|
/// Notes a live event on a listed channel that changes the channel itself.
|
|
/// Returns whether it was one.
|
|
bool _noteChannelChange(NostrEvent event) {
|
|
final changed =
|
|
event.kind == EventKind.nip29EditMetadata ||
|
|
(event.kind == EventKind.systemMessage &&
|
|
_channelChangeSystemTypes.contains(_systemMessageType(event)));
|
|
if (changed) _noteListChanged();
|
|
return changed;
|
|
}
|
|
|
|
/// Subscribes to [_channelListNoticeKinds] unless already subscribed. The
|
|
/// notifier rebuilds when the relay or identity changes, so one subscription
|
|
/// serves its whole lifetime. A refused or failed subscription is retried
|
|
/// with backoff. Notices sent while it was down are not replayed, so
|
|
/// reopening it ([isRetry]) schedules a read (see
|
|
/// [_ChannelsNotifierLiveSubscriptions._noteReopenedSubscriptions]).
|
|
Future<void> _subscribeChannelListNotices(
|
|
String myPk, {
|
|
bool isRetry = false,
|
|
}) async {
|
|
if (_listNoticesSubscribed) return;
|
|
_listNoticesSubscribed = true;
|
|
_listNoticesRetry.cancelPending();
|
|
final generation = ++_listNoticesGeneration;
|
|
var closed = false;
|
|
try {
|
|
final unsubscribe = await _lifecycleRef
|
|
.read(relaySessionProvider.notifier)
|
|
.subscribeWithStatus(
|
|
NostrFilter(
|
|
kinds: _channelListNoticeKinds,
|
|
tags: {
|
|
'#p': [myPk],
|
|
},
|
|
limit: 0,
|
|
),
|
|
(_) {
|
|
if (generation == _listNoticesGeneration) _noteListChanged();
|
|
},
|
|
onClosed: (message) {
|
|
if (generation != _listNoticesGeneration) return;
|
|
closed = true;
|
|
_listNoticesUnsubscribe = null;
|
|
_listNoticesInterrupted = false;
|
|
debugPrint(
|
|
'[ChannelsNotifier] channel list notices closed: $message',
|
|
);
|
|
if (_isRelayCapacityClose(message)) {
|
|
_retryChannelListNotices(myPk);
|
|
} else {
|
|
_listNoticesRefused = true;
|
|
}
|
|
},
|
|
// RelaySession reopens a REQ the relay closed for a transient
|
|
// reason itself, and reports it only here.
|
|
onStatusChanged: (status) {
|
|
if (generation != _listNoticesGeneration) return;
|
|
if (status == RelaySubscriptionStatus.retrying) {
|
|
_listNoticesInterrupted = true;
|
|
} else if (_listNoticesInterrupted) {
|
|
_listNoticesInterrupted = false;
|
|
_listNoticesReopened = true;
|
|
_scheduleListRead();
|
|
}
|
|
},
|
|
);
|
|
if (generation != _listNoticesGeneration || closed) {
|
|
unsubscribe();
|
|
return;
|
|
}
|
|
_listNoticesUnsubscribe = unsubscribe;
|
|
if (isRetry) {
|
|
_listNoticesReopened = true;
|
|
_listNoticesRetry.opened();
|
|
_scheduleListRead();
|
|
}
|
|
} catch (error) {
|
|
// A refusal before readiness also throws; onClosed has handled it.
|
|
if (generation != _listNoticesGeneration || _listNoticesRefused) return;
|
|
debugPrint('[ChannelsNotifier] channel list notices failed: $error');
|
|
_retryChannelListNotices(myPk);
|
|
}
|
|
}
|
|
|
|
void _retryChannelListNotices(String myPk) {
|
|
_listNoticesSubscribed = false;
|
|
_listNoticesRetry.schedule(() {
|
|
// Disconnected: the reconnect's list read subscribes again.
|
|
if (!_lifecycleRef.mounted ||
|
|
_lifecycleRef.read(relaySessionProvider).status !=
|
|
SessionStatus.connected) {
|
|
return;
|
|
}
|
|
unawaited(_subscribeChannelListNotices(myPk, isRetry: true));
|
|
});
|
|
}
|
|
|
|
void _clearChannelListNotices() {
|
|
_listNoticesGeneration++;
|
|
_listNoticesRetry.cancel();
|
|
_listNoticesReopened = false;
|
|
_listNoticesInterrupted = false;
|
|
_listNoticesRefused = false;
|
|
_listNoticesUnsubscribe?.call();
|
|
_listNoticesUnsubscribe = null;
|
|
_listNoticesSubscribed = false;
|
|
}
|
|
}
|
|
|
|
/// Whether the relay closed a REQ for lack of capacity, which can clear on
|
|
/// its own. Its other terminal reasons (`restricted:`, `invalid:` and so on)
|
|
/// cannot succeed unchanged on this connection, so those REQs are not retried.
|
|
bool _isRelayCapacityClose(String message) =>
|
|
message.trim().toLowerCase().startsWith('error: too many subscriptions');
|
|
|
|
String? _systemMessageType(NostrEvent event) {
|
|
try {
|
|
final content = jsonDecode(event.content);
|
|
return content is Map ? content['type'] as String? : null;
|
|
} on FormatException {
|
|
return null;
|
|
} on TypeError {
|
|
return null;
|
|
}
|
|
}
|