Files
buzz/mobile/lib/shared/relay/relay_session_snapshot.dart
Tom Brow 5e36d65c9e fix(mobile): inflate gzip read-state snapshot responses (#9089)
On relays behind a CDN that gzips responses (the Builderlab relay does),
mobile read state never synced. Every read-state snapshot fetch, and
therefore every read-mark publish, failed with `FormatException:
Unexpected extension byte`, so read marks made on the phone never
reached other devices and each reconnect retried and failed again.

The relay query transport deliberately leaves gzip bodies compressed so
they can be inflated off the UI isolate (see `RelayHttpQueryClient`),
but the snapshot path decoded the raw bytes with `utf8.decode`. It now
uses `relayResponseText`, like the other query callers, for both the
discovery and the snapshot responses.

Heads-up for reviewers: with the snapshot working, a resume also pays
for the full snapshot download on top of the existing read-state replay
on the live subscription. A follow-up PR removes that replay.

### Validation

- Added test: `inflates gzip discovery and snapshot bodies` serves both
responses gzipped. Without the fix it fails with the same `Unexpected
extension byte` error seen on the device.
- Full mobile suite: all pass except the known stale
`fullscreen_onboarding_test` case, which fails on main too.
- iPhone 12 mini (Profile build, Builderlab community): before, every
resume logged `snapshot failed` and `publish failed (journal retained)`.
After, the snapshot on resume and the snapshot inside a publish both
completed with no errors.
- Automated app run on the same phone with this change: Home
backgrounded past the reconnect grace period and resumed, then search
and a large channel opened. 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>
2026-11-05 11:14:39 -08:00

107 lines
3.4 KiB
Dart

part of 'relay_session.dart';
extension on RelaySessionNotifier {
Future<List<NostrEvent>> _fetchReadStateSnapshot({
required Duration timeout,
}) async {
if (_disposed || _ageRestricted) {
throw StateError('Relay session is unavailable');
}
final generation = _contextGeneration;
final config = _snapshotConfig;
final nsec = config.nsec;
if (nsec == null || nsec.isEmpty) {
throw StateError('Snapshot requires a signing identity');
}
final viewer = nostr.Keys(nsec).public;
void checkContext() {
if (_disposed ||
_ageRestricted ||
generation != _contextGeneration ||
_snapshotConfig.baseUrl != config.baseUrl ||
_snapshotConfig.nsec != nsec) {
throw StateError('Snapshot belongs to a retired session');
}
}
Future<http.Response> send(http.Request request, int maxBytes) async {
final response = await _httpQueryClient.sendBounded(
request,
maxBytes: maxBytes,
timeout: timeout,
decorate: (client, active) => HostedRelayHttpClient(
_snapshotAuth,
config,
inner: client,
canSend: () =>
active() && !_disposed && generation == _contextGeneration,
),
);
checkContext();
if (response.statusCode < 200 || response.statusCode >= 300) {
final text = relayResponseText(
response.bodyBytes,
response.headers['content-type'],
maxInflatedBytes: maxBytes,
);
_activateRateLimitGateFromHttpError(text);
throw RelayException(response.statusCode, text);
}
return response;
}
final origin = Uri.parse(config.baseUrl);
final discovery = http.Request('GET', origin.resolve('/'))
..headers['Accept'] = 'application/nostr+json';
// The query transport leaves gzip bodies compressed (see
// RelayHttpQueryClient), and the relay's CDN gzips both responses. The
// inflated size is capped too: the transport cap only sees the
// compressed bytes.
final discovered = await send(discovery, 64 * 1024);
final info = jsonDecode(
relayResponseText(
discovered.bodyBytes,
discovered.headers['content-type'],
maxInflatedBytes: 64 * 1024,
),
);
final descriptor = info is Map<String, dynamic>
? info['read_state_snapshot']
: null;
final community = readStateSnapshotCommunity(descriptor);
final url = origin.resolve('/query');
final body = utf8.encode(
jsonEncode([
{
'kinds': [30078],
'authors': [viewer],
'read_state_snapshot': 1,
},
]),
);
checkContext();
final request = http.Request('POST', url)
..bodyBytes = body
..headers.addAll({
'Content-Type': 'application/json',
'Authorization': buildNip98AuthHeader(
method: 'POST',
url: url.toString(),
bodyBytes: body,
nsec: nsec,
),
});
final response = await send(request, readStateSnapshotMaxEnvelopeBytes);
// Inflating, parsing and Schnorr verification must not block Flutter's
// UI isolate.
final events = await _snapshotDecoder((
bytes: response.bodyBytes,
contentType: response.headers['content-type'],
viewer: viewer,
community: community,
));
checkContext();
return events;
}
}