mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
Makes relay errors that nothing catches readable in diagnostic reports. Today an unhandled relay rejection or timeout arrives with its text removed and a stack that stops at the async error handler, so a report can't say which call failed or why. ## Changes - **Typed call and reason:** relay errors now carry the call (`publish`, `query`, `history`, `subscribe`) and a fixed reason class taken from the relay's reason prefix (`invalid`, `rate-limited`, `restricted`, `auth-required`, `blocked`, `duplicate`, `pow`, `unsupported`, `error`, `timeout`, or `other`). Types: - `RelayEventRejectedException` implements the new `RelayCallError`; - new `RelayTimeoutException` extends `TimeoutException`, and `RelayAckTimeoutError` now extends it; - new `RelayClosedException` replaces the plain `Exception` for a closed history or live subscription, with the same `toString`. - new `RelayQueryException` (a `RelayException` that is also a `RelayCallError`) for a non-2xx `/query` answer, with its reason from the status alone; - a one-shot signed event the relay refuses now fails with a typed rejection, with the same text. Existing `TimeoutException` checks and message helpers behave as before. - **Report tags:** before the filter runs, a report whose error is a `RelayCallError` gets `relay.call` and `relay.reason` tags. The relay's own text is never sent. These reports are also grouped by call and reason on top of the default grouping, so a rate limit and an invalid request from the same code become separate issues. - **Call-site stack:** pending publishes, one-shot signed events, and history and live subscriptions keep the stack where they were created, and errors completed later from timers or socket callbacks use it. A report's stack now reaches the calling code. - **Spec:** one bullet on the tags, the grouping and the stack. ## Validation New tests: - a table of reason prefixes to classes; - error types, fields and the existing message helpers; - relay session cases: a rejected publish's call, reason and calling stack, the timeout types, and closed subscriptions; - reports: tags, the grouping key, no relay text, and non-relay errors untouched. - production refusals through a serialized report: `/query` statuses, snapshot `/query` versus discovery, and one-shot rejections and timeouts with the caller's stack. Full-app run on an iOS simulator (signed in, healthy relay): cold start and session restore, channel list, opening channels and DMs, history back to each channel's start, send, react, edit, thread reply, search, channel details and Add Members, Settings > Send test report, and background then foreground followed by a send and a delete. All passed with no new errors in the device log, and no doubled error names in any logged text. Error paths (timeouts, closed connections, relay rejections) weren't triggered on the healthy relay; the unit tests above cover them. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
231 lines
7.4 KiB
Dart
231 lines
7.4 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), 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), 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();
|
|
}
|
|
}
|