Files
buzz/mobile/lib/shared/relay/relay_http_query_client.dart
Tom Brow e421ac9870 perf(mobile): trim relay call-site stacks and capture them before async waits (#9949)
## Summary

Two follow-ups to the call-site stacks that escaped relay errors carry:

- **Trim:** Sentry parses a whole stack synchronously and has no cap, so
a call-site stack is now cut to its innermost 64 lines (async gap lines
included). When the kept lines hold no `<asynchronous suspension>` line,
one is added after them, so Sentry's stack parser still reads it as a VM
stack directly instead of first scanning it for other formats. The cut
is made when the stack is first formatted, so an error its caller
discards costs no formatting. One `completeErrorAt` helper next to the
error types applies it at every completion site, and query timeouts
throw with the cut stack too.
- **Capture at entry:** `publish`, `fetchHistory` and
`SignedEventRelay.submit` took their call site after the rate-limit
wait, `mayPublish` or `onSigned`. A caller that doesn't await the call
was already gone from the stack by then, so its frame was missing. The
call site is now taken before the first `await`. `submit` re-stacks
relay call errors from `publish` with its own entry stack, since
`publish` only starts after `onSigned`.

### Validation

Added tests: [stack
trimming](https://github.com/block/buzz/blob/tomb/mobile-relay-stack-trim/mobile/test/shared/relay/relay_call_error_test.dart)
(a deep stack is cut to the cap and keeps the frames nearest the call; a
short one is kept whole; a cut stack keeps exactly one async gap
wherever its first gap falls; the stack is formatted only when read, and
only once), and [capture before the
wait](https://github.com/block/buzz/blob/tomb/mobile-relay-stack-trim/mobile/test/shared/relay/relay_session_test.dart)
for a publish and a history request held by the rate limit and a submit
held by `onSigned`, each checking that the caller's frame is on the
completed error's stack.


Full-app check on an iOS simulator signed in to a Builderlab community:
the channel list loads, opening two channels fetches their history, and
a sent message publishes and shows as sent. No relay call errors logged.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-25 15:05:52 -08:00

237 lines
7.5 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'package:buzz/shared/http/app_http_client.dart';
import 'relay_call_error.dart';
import 'relay_query_response.dart' show RelayResponseTooLarge;
/// The default transport. On iOS and Android, the app-wide native session
/// inflates gzip natively, off the Dart isolate. `dart:io` would inflate on
/// the calling isolate, so leave its responses compressed for the response
/// decoder.
///
/// A non-`dart:io` client supplied through `http.runWithClient`, such as a
/// `MockClient`, is used as is. An `IOClient` is replaced, not closed, since
/// it may be shared.
http.Client _defaultTransport() {
if (hasNativeHttpSession) return newAppHttpClient();
final client = http.Client();
if (client is! IOClient) return countedAppHttpClient(client);
return countedAppHttpClient(IOClient(HttpClient()..autoUncompress = false));
}
/// Owns the reusable HTTP transport used for relay `/query` requests.
///
/// Requests advertise gzip. A response body may therefore come back
/// compressed; decode it with `relayResponseText` or `decodeRelayQueryResponse`.
class RelayHttpQueryClient {
RelayHttpQueryClient({
http.Client? client,
http.Client Function()? clientFactory,
}) : _injectedClient = client,
_clientFactory = clientFactory ?? _defaultTransport;
final http.Client? _injectedClient;
final http.Client Function() _clientFactory;
_ClientGeneration? _currentGeneration;
final Set<_ClientGeneration> _generations = {};
/// The error for a request that outlived [timeout]: a [call] when the
/// request is one, otherwise a plain [TimeoutException]. Its stack is the
/// caller's, since the timer that raises it has no frames from the app.
static TimeoutException _timedOut(Duration timeout, RelayCall? call) =>
call == null
? TimeoutException('Relay request timed out after $timeout', timeout)
: RelayTimeoutException(
call,
'Relay query timed out after $timeout',
timeout,
);
Future<http.Response> post(
Uri url, {
required Map<String, String> headers,
required List<int> body,
required Duration timeout,
http.Client Function(http.Client, bool Function())? decorate,
}) async {
final callSite = StackTrace.current;
final generation = _injectedClient == null
? (_currentGeneration ??= _createGeneration())
: null;
generation?.acquire();
var active = true;
// Retiring a generation cannot stop a request on a shared session, so a
// timed-out request is aborted rather than left holding bandwidth.
final abort = Completer<void>();
final request =
http.AbortableRequest('POST', url, abortTrigger: abort.future)
..followRedirects = false
..headers['Accept-Encoding'] = 'gzip'
..headers.addAll(headers)
..bodyBytes = body;
try {
final transport = _injectedClient ?? generation!.client;
final client = decorate?.call(transport, () => active) ?? transport;
return await client
.send(request)
.then(http.Response.fromStream)
.timeout(timeout);
} on TimeoutException {
noteHttpDeadline(request);
if (!abort.isCompleted) abort.complete();
if (identical(_currentGeneration, generation)) {
_currentGeneration = null;
}
generation?.retire();
Error.throwWithStackTrace(
_timedOut(timeout, RelayCall.query),
trimCallSite(callSite),
);
} finally {
active = false;
generation?.release();
}
}
/// Sends a non-redirecting request, bounding bytes before buffering or parsing.
/// The deadline includes headers and the entire response body. A timeout is
/// a [RelayTimeoutException] for [call], or untyped when [call] is null.
Future<http.Response> sendBounded(
http.Request request, {
required int maxBytes,
required Duration timeout,
required RelayCall? call,
http.Client Function(http.Client, bool Function())? decorate,
}) async {
final callSite = StackTrace.current;
// As in [post], a timed-out request on a shared session is aborted.
final abort = Completer<void>();
final sent =
http.AbortableRequest(
request.method,
request.url,
abortTrigger: abort.future,
)
..followRedirects = false
..headers.addAll(request.headers)
..bodyBytes = request.bodyBytes;
final generation = _injectedClient == null
? (_currentGeneration ??= _createGeneration())
: null;
generation?.acquire();
StreamIterator<List<int>>? iterator;
var finished = false;
Future<http.Response> receive() async {
final transport = _injectedClient ?? generation!.client;
final client = decorate?.call(transport, () => !finished) ?? transport;
final response = await client.send(sent);
if (finished) {
await response.stream.listen(null).cancel();
throw StateError('Relay request already timed out');
}
iterator = StreamIterator(response.stream);
if ((response.contentLength ?? 0) > maxBytes) {
throw const RelayResponseTooLarge('Relay response exceeds byte limit');
}
final bytes = <int>[];
while (await iterator!.moveNext()) {
final chunk = iterator!.current;
if (bytes.length + chunk.length > maxBytes) {
throw const RelayResponseTooLarge(
'Relay response exceeds byte limit',
);
}
bytes.addAll(chunk);
}
iterator = null; // An exhausted stream needs no cancellation.
return http.Response.bytes(
bytes,
response.statusCode,
headers: response.headers,
request: request,
);
}
try {
return await receive().timeout(timeout);
} on TimeoutException {
noteHttpDeadline(sent);
if (!abort.isCompleted) abort.complete();
if (identical(_currentGeneration, generation)) {
_currentGeneration = null;
}
generation?.retire();
Error.throwWithStackTrace(
_timedOut(timeout, call),
trimCallSite(callSite),
);
} finally {
finished = true;
// Cancelling an iterator that never listened leaves the body
// downloading on a shared session, so abort on every exit.
if (!abort.isCompleted) abort.complete();
if (iterator != null) await iterator!.cancel();
generation?.release();
}
}
void close() {
for (final generation in _generations.toList()) {
generation.close();
}
_currentGeneration = null;
_injectedClient?.close();
}
_ClientGeneration _createGeneration() {
late final _ClientGeneration generation;
generation = _ClientGeneration(
_clientFactory(),
onClosed: () => _generations.remove(generation),
);
_generations.add(generation);
return generation;
}
}
class _ClientGeneration {
_ClientGeneration(this.client, {required this.onClosed});
final http.Client client;
final void Function() onClosed;
int _activeRequests = 0;
bool _retired = false;
bool _closed = false;
void acquire() {
assert(!_closed);
_activeRequests++;
}
void release() {
assert(_activeRequests > 0);
_activeRequests--;
_closeIfIdle();
}
void retire() {
_retired = true;
_closeIfIdle();
}
void close() {
if (_closed) return;
_closed = true;
client.close();
onClosed();
}
void _closeIfIdle() {
if (_retired && _activeRequests == 0) close();
}
}