mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
Every time the mobile app reconnects (for example after more than 5 seconds in the background), the read-state live subscription asked the relay for up to 500 stored read-state events. That re-downloaded every read-state slot on the account, then the snapshot fetched the same events again right after. On a heavy account (28 slots) that replay alone was about 1.4 MB per resume. The live subscription now uses `limit: 0`, so it only delivers changes. It still opens before the snapshot, so the snapshot covers anything published in between. The subscription can also go live after `subscribe` has returned: on a cold start with slow AUTH, `subscribe` returns on its 500 ms fallback before the REQ is registered, after a transient CLOSED (rate limit, capacity) the session reopens it on the same socket, and a reconnect replays it. With `limit: 0` nothing replays marks published in that gap, so the manager reads the snapshot every time the subscription reports ready, as the channel list's `limit: 0` subscription already does. The session keeps live subscriptions across reconnects and replays them on the new socket, so a reconnect no longer resubscribes: the replay's ready reads the snapshot, once per reconnect. The manager opens a new subscription only after losing one (a terminal CLOSED or a failed subscribe), on the next reconnect. All snapshot reads outside a publish go through one sync loop. Initialize and each ready ask that loop for a snapshot. A request made before the current pass starts its read joins that read, and a request made during the read runs one more pass, so a ready can't be swallowed by a read already in flight. This needs no generation or ready-transition checks, at the cost of an occasional extra read (for example a cold start whose ready lands after the 500 ms fallback, when the first read has already started). Snapshot reads are numbered in start order, including a publish's own read, and only a read newer than every settled one decides whether the last snapshot succeeded. An older read finishing late cannot clear the retry a newer failed read needs. A failed read waits for the next trigger: the publish it schedules, which reads the snapshot in full after a failure, or a later ready, resume or reconnect. A publish with nothing to send skips its snapshot ([#9093 skip redundant publish](https://github.com/block/buzz/pull/9093)) only when the last snapshot succeeded, so after a failed resume snapshot the next publish still retries it. A publish snapshot now notifies readers of the marks it merged, since unchanged slots publish nothing whose echo would. ### Accepted gap If the snapshot fails (timeout, discovery or HTTP error) on a device with no local journal, read state stays local until the next successful snapshot, which every resume, reconnect, subscription recovery and publish retries. Falling back to a stored replay on failure would close the gap, but it adds a late subscription path for a rare failure that already heals on its own. ### Validation - Added test: `live subscription replays nothing and opens before the snapshot`. It fails without the change (`limit` 500). - Added test: `a clean reconnect through the real session replays one REQ and reads the snapshot once, and a lost subscription is reopened` drives the real `RelaySessionNotifier` with a recording socket: the connected listener runs, then the session's replay, then EOSE. It fails against the previous revision of this PR (two `l-2` REQs and two snapshot reads per reconnect). After a terminal CLOSED, the next reconnect opens a new subscription and reads the snapshot. - Added test: `readies during a held snapshot read share one more read`. - Added test: `a mark published while the live subscription retries is read once it recovers` puts the subscription into retry, lets another device publish a mark, then reports it ready. It fails without the read on ready. - Added test: `a failed late-ready read is retried by the next publish`. It fails without the retry. - Added test: `a reconnect while the first snapshot downloads is not swallowed by the cold-start connect` lets the cold-start connect queue behind initialize, then reconnects while the first read is still downloading and has a peer publish a mark. It fails against the previous revision of this PR (the queued pass swallowed the reconnect) and passes with the sync loop. - Added test: `an older snapshot finishing late keeps a newer failed read's retry` holds a publish's snapshot read, fails a newer read, then lets the older one finish. It fails against the previous revision of this PR (the older success cleared the retry) and passes with the read ordering. - Added test: `a mark published before a slow cold-start REQ goes live is read then` lets `subscribe` return before ready, publishes a mark, then reports ready. It fails without the read on ready. - `a publish after a failed snapshot retries it, then skips again` replaces the earlier skipped-publish test and fails without the snapshot check. It also checks that the retried snapshot's new marks notify readers, which fails without the notify. - Read-state suite (95 tests), `flutter analyze` and the full mobile suite pass. - iPhone 12 mini, Profile build with [#9089 gzip snapshot](https://github.com/block/buzz/pull/9089) applied, Home backgrounded 12 s and resumed, websocket bytes received in the 15 s after resume: | | Websocket in | Read-state replay | | --- | --- | --- | | Before (gzip fix only) | 2,087 KB | 1,458 KB (28 events) | | After (gzip fix + this) | 575 KB | none | The table counts websocket bytes only. Each resume reads the read-state snapshot once over HTTP, before and after this change. Automated app run on the same phone: Home, a large channel and search resumed after the reconnect grace period, with no read-state errors logged. Read marks were not compared across devices. 🤖 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: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
386 lines
12 KiB
Dart
386 lines
12 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:buzz/features/activity/compose_drafts_provider.dart';
|
|
import 'package:buzz/features/channels/channel.dart';
|
|
import 'package:buzz/features/channels/channels_provider.dart';
|
|
import 'package:buzz/features/channels/quick_send_host.dart';
|
|
import 'package:buzz/shared/me/default_agent.dart';
|
|
import 'package:buzz/shared/relay/relay.dart';
|
|
import 'package:buzz/shared/theme/theme.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
import 'package:pointycastle/digests/sha256.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class _EmptyChannels extends ChannelsNotifier {
|
|
@override
|
|
Future<List<Channel>> build() async => [];
|
|
}
|
|
|
|
class _Lifecycle extends AppLifecycleNotifier {
|
|
@override
|
|
AppLifecycleState build() => AppLifecycleState.resumed;
|
|
|
|
void background() => state = AppLifecycleState.paused;
|
|
}
|
|
|
|
class _Config extends RelayConfigNotifier {
|
|
_Config(this.config);
|
|
final RelayConfig config;
|
|
@override
|
|
RelayConfig build() => config;
|
|
}
|
|
|
|
/// A relay that is not connected until the test says so, accepts every
|
|
/// publish and serves back the DM its open command finds or creates.
|
|
class _Relay extends RelaySessionNotifier {
|
|
_Relay(this.owner, this.profile);
|
|
final nostr.Keys owner;
|
|
final NostrEvent profile;
|
|
final published = <NostrEvent>[];
|
|
|
|
/// Rejects the next message the way an over-quota relay does.
|
|
var rateLimitNextMessage = false;
|
|
|
|
/// Loses the next message's answer, so it may or may not have landed.
|
|
var timeOutNextMessage = false;
|
|
|
|
/// Drops the socket just before the next message goes out.
|
|
var dropBeforeNextMessage = false;
|
|
final _stored = <NostrEvent>[];
|
|
static const dmId = 'bestie-dm';
|
|
|
|
@override
|
|
SessionState build() =>
|
|
const SessionState(status: SessionStatus.disconnected);
|
|
|
|
void connect() => state = const SessionState(status: SessionStatus.connected);
|
|
|
|
/// Background pauses started; the real session closes the socket after one.
|
|
var pauses = 0;
|
|
|
|
@override
|
|
void onAppPaused() => pauses++;
|
|
|
|
@override
|
|
void onAppResumed() => connect();
|
|
|
|
NostrEvent _sign(int kind, List<List<String>> tags) => NostrEvent.fromJson(
|
|
nostr.Event.from(
|
|
kind: kind,
|
|
content: '',
|
|
secretKey: owner.secret,
|
|
tags: tags,
|
|
).toMap(),
|
|
);
|
|
|
|
@override
|
|
Future<List<NostrEvent>> queryRelay(
|
|
List<NostrFilter> filters, {
|
|
Duration timeout = const Duration(seconds: 8),
|
|
}) async => [profile];
|
|
|
|
@override
|
|
Future<List<NostrEvent>> fetchHistory(
|
|
NostrFilter filter, {
|
|
Duration timeout = const Duration(seconds: 8),
|
|
}) async {
|
|
if (filter.kinds.contains(0)) return [profile];
|
|
final ds = filter.tags['#d'];
|
|
return _stored.reversed
|
|
.where(
|
|
(e) =>
|
|
filter.kinds.contains(e.kind) &&
|
|
(ds == null || ds.contains(e.getTagValue('d'))),
|
|
)
|
|
.take(filter.limit)
|
|
.toList();
|
|
}
|
|
|
|
@override
|
|
Future<void Function()> subscribeWithStatus(
|
|
NostrFilter filter,
|
|
void Function(NostrEvent) onEvent, {
|
|
void Function(String message)? onClosed,
|
|
required void Function(RelaySubscriptionStatus status) onStatusChanged,
|
|
bool resumeSince = true,
|
|
}) async => () {};
|
|
|
|
@override
|
|
Future<NostrEvent> publish(
|
|
NostrEvent event, {
|
|
Duration timeout = const Duration(seconds: 8),
|
|
}) async {
|
|
if (event.kind == 9 && rateLimitNextMessage) {
|
|
rateLimitNextMessage = false;
|
|
throw Exception('rate-limited: quota exceeded; retry in 0s');
|
|
}
|
|
if (event.kind == 9 && dropBeforeNextMessage) {
|
|
dropBeforeNextMessage = false;
|
|
throw StateError('Relay session is not connected');
|
|
}
|
|
if (event.kind == 9 && timeOutNextMessage) {
|
|
timeOutNextMessage = false;
|
|
throw TimeoutException('no OK');
|
|
}
|
|
published.add(event);
|
|
if (event.kind != 41010) return event;
|
|
// Opening is find-or-create: the relay answers with the one DM.
|
|
if (!_stored.any((e) => e.getTagValue('d') == dmId)) {
|
|
final peer = event.getTagValue('p')!;
|
|
_stored.add(
|
|
_sign(39000, [
|
|
['d', dmId],
|
|
['name', 'DM'],
|
|
['t', 'dm'],
|
|
['private'],
|
|
['hidden'],
|
|
['p', owner.public],
|
|
['p', peer],
|
|
]),
|
|
);
|
|
_stored.add(
|
|
_sign(39002, [
|
|
['d', dmId],
|
|
['p', owner.public, '', 'member'],
|
|
['p', peer, '', 'bot'],
|
|
]),
|
|
);
|
|
}
|
|
return NostrEvent(
|
|
id: event.id,
|
|
pubkey: event.pubkey,
|
|
createdAt: event.createdAt,
|
|
kind: event.kind,
|
|
tags: event.tags,
|
|
content: 'response:${jsonEncode({'channel_id': dmId, 'created': true})}',
|
|
sig: event.sig,
|
|
);
|
|
}
|
|
}
|
|
|
|
void main() {
|
|
testWidgets('Siri quick send posts in the Bestie DM', (tester) async {
|
|
const channel = MethodChannel('buzz/quick_send');
|
|
final platformCalls = <String>[];
|
|
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
|
call,
|
|
) async {
|
|
platformCalls.add(call.method);
|
|
return null;
|
|
});
|
|
addTearDown(
|
|
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
|
channel,
|
|
null,
|
|
),
|
|
);
|
|
SharedPreferences.setMockInitialValues({});
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final owner = nostr.Keys.generate(), bestie = nostr.Keys.generate();
|
|
final digest = SHA256Digest()
|
|
.process(
|
|
Uint8List.fromList(utf8.encode('nostr:agent-auth:${bestie.public}:')),
|
|
)
|
|
.map((v) => v.toRadixString(16).padLeft(2, '0'))
|
|
.join();
|
|
final profile = NostrEvent.fromJson(
|
|
nostr.Event.from(
|
|
kind: 0,
|
|
content: jsonEncode({'display_name': 'Bestie'}),
|
|
secretKey: bestie.secret,
|
|
tags: [
|
|
[
|
|
'auth',
|
|
owner.public,
|
|
'',
|
|
nostr.Schnorr.sign(secretKey: owner.secret, message: digest),
|
|
],
|
|
],
|
|
).toMap(),
|
|
);
|
|
final relay = _Relay(owner, profile);
|
|
String? chosenBestie;
|
|
await tester.pumpWidget(
|
|
ProviderScope(
|
|
overrides: [
|
|
savedPrefsProvider.overrideWithValue(prefs),
|
|
relayConfigProvider.overrideWith(
|
|
() => _Config(
|
|
RelayConfig(baseUrl: 'https://relay.test', nsec: owner.nsec),
|
|
),
|
|
),
|
|
relaySessionProvider.overrideWith(() => relay),
|
|
defaultAgentProvider.overrideWith(
|
|
(ref) => Stream.value(chosenBestie),
|
|
),
|
|
channelsProvider.overrideWith(_EmptyChannels.new),
|
|
appLifecycleProvider.overrideWith(_Lifecycle.new),
|
|
],
|
|
child: MaterialApp(
|
|
theme: AppTheme.light(),
|
|
home: const QuickSendHost(),
|
|
),
|
|
),
|
|
);
|
|
await tester.pumpAndSettle();
|
|
expect(platformCalls, ['ready'], reason: 'Siri can send once Home is up');
|
|
|
|
// Siri calls the host the way QuickSend.swift does and gets its reply.
|
|
Future<(Object?, PlatformException?)> siri(
|
|
String method, [
|
|
Object? arguments,
|
|
]) async {
|
|
Object? result;
|
|
PlatformException? failure;
|
|
var replied = false;
|
|
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
|
|
channel.name,
|
|
channel.codec.encodeMethodCall(MethodCall(method, arguments)),
|
|
(reply) {
|
|
try {
|
|
result = channel.codec.decodeEnvelope(reply!);
|
|
} on PlatformException catch (e) {
|
|
failure = e;
|
|
}
|
|
replied = true;
|
|
},
|
|
);
|
|
// Ownership verification runs in a real isolate.
|
|
for (var i = 0; i < 100 && !replied; i++) {
|
|
await tester.pump(const Duration(milliseconds: 50));
|
|
await tester.runAsync(
|
|
() => Future<void>.delayed(const Duration(milliseconds: 50)),
|
|
);
|
|
}
|
|
expect(replied, isTrue, reason: '$method never answered');
|
|
return (result, failure);
|
|
}
|
|
|
|
final container = ProviderScope.containerOf(
|
|
tester.element(find.byType(QuickSendHost)),
|
|
);
|
|
container.read(relaySessionProvider);
|
|
relay.connect();
|
|
await tester.pump();
|
|
|
|
final (_, noBestie) = await siri('bestie');
|
|
expect(noBestie?.code, 'failed');
|
|
expect(noBestie?.message, 'Choose a Bestie in Buzz first.');
|
|
|
|
chosenBestie = bestie.public;
|
|
container.invalidate(defaultAgentProvider);
|
|
await tester.pump();
|
|
final (named, _) = await siri('bestie');
|
|
final scope = (named! as Map)['scope'];
|
|
expect(named, {'pubkey': bestie.public, 'name': 'Bestie', 'scope': scope});
|
|
|
|
// A confirmation from before a community switch can't send here.
|
|
final (_, switched) = await siri('send', {
|
|
'text': 'Remind me to call Sam',
|
|
'bestie': bestie.public,
|
|
'scope': 'https://other.test $scope',
|
|
});
|
|
expect(switched?.message, contains('switched communities'));
|
|
|
|
final (_, blank) = await siri('send', {
|
|
'text': ' \n ',
|
|
'bestie': bestie.public,
|
|
'scope': scope,
|
|
});
|
|
expect(blank?.code, 'failed');
|
|
expect(blank?.message, 'Say a message.');
|
|
expect(relay.published, isEmpty);
|
|
|
|
// Buzz sat in the background long enough for its socket to close.
|
|
(container.read(appLifecycleProvider.notifier) as _Lifecycle).background();
|
|
relay.state = const SessionState(status: SessionStatus.disconnected);
|
|
final pausesBefore = relay.pauses;
|
|
// Its catch-up used the write quota, so the first try is turned away.
|
|
relay.rateLimitNextMessage = true;
|
|
await tester.pumpAndSettle();
|
|
final (_, failure) = await siri('send', {
|
|
'text': ' Remind me to call Sam ',
|
|
'bestie': bestie.public,
|
|
'scope': scope,
|
|
});
|
|
expect(failure, isNull);
|
|
expect(
|
|
relay.pauses,
|
|
pausesBefore + 1,
|
|
reason: 'The send hands the session back to its background pause',
|
|
);
|
|
|
|
final open = relay.published.singleWhere((e) => e.kind == 41010);
|
|
expect(open.pubkey, owner.public);
|
|
expect(open.tags, [
|
|
['p', bestie.public],
|
|
]);
|
|
final first = relay.published.singleWhere((e) => e.kind == 9);
|
|
expect(first.content, 'Remind me to call Sam');
|
|
expect(first.pubkey, owner.public);
|
|
expect(first.getTagValue('h'), _Relay.dmId);
|
|
expect(first.tags, contains(equals(['p', bestie.public])));
|
|
|
|
// A sent message leaves the DM's draft as it was.
|
|
final drafts = container.read(composeDraftsProvider.notifier);
|
|
drafts.save(
|
|
key: _Relay.dmId,
|
|
channelId: _Relay.dmId,
|
|
text: 'Half a @Sam',
|
|
mentionKeys: {'Sam': 'sam-pubkey'},
|
|
);
|
|
|
|
// A second quick send goes to the same DM.
|
|
final (_, again) = await siri('send', {
|
|
'text': 'And buy milk',
|
|
'bestie': bestie.public,
|
|
'scope': scope,
|
|
});
|
|
expect(again, isNull);
|
|
final messages = relay.published.where((e) => e.kind == 9).toList();
|
|
expect(messages.map((e) => e.content), [
|
|
'Remind me to call Sam',
|
|
'And buy milk',
|
|
]);
|
|
expect(messages.map((e) => e.getTagValue('h')).toSet(), {_Relay.dmId});
|
|
expect(drafts.textFor(_Relay.dmId), 'Half a @Sam');
|
|
|
|
// When Buzz can't tell whether a send landed, the text stays in the DM's
|
|
// draft, after the person's own, and Siri says to check before resending.
|
|
relay.timeOutNextMessage = true;
|
|
final (_, unsure) = await siri('send', {
|
|
'text': 'Call back',
|
|
'bestie': bestie.public,
|
|
'scope': scope,
|
|
});
|
|
expect(
|
|
unsure?.message,
|
|
"Buzz isn't sure that sent. Check your Bestie DM before trying again.",
|
|
);
|
|
final kept = drafts.draftFor(_Relay.dmId)!;
|
|
expect(kept.text, 'Half a @Sam\n\nCall back');
|
|
expect(kept.mentionKeys, {'Sam': 'sam-pubkey'});
|
|
|
|
// A socket that drops just before the message goes out keeps it too.
|
|
relay.dropBeforeNextMessage = true;
|
|
final (_, dropped) = await siri('send', {
|
|
'text': 'Then Sam',
|
|
'bestie': bestie.public,
|
|
'scope': scope,
|
|
});
|
|
expect(dropped?.message, contains('Check your Bestie DM'));
|
|
expect(drafts.textFor(_Relay.dmId), 'Half a @Sam\n\nCall back\n\nThen Sam');
|
|
|
|
// Leaving Home, for example on sign-out, takes the handler with it.
|
|
await tester.pumpWidget(const SizedBox());
|
|
expect(platformCalls, ['ready', 'unready']);
|
|
// Let the sent messages' local animations finish.
|
|
await tester.pump(const Duration(seconds: 10));
|
|
});
|
|
}
|