mirror of
https://github.com/block/buzz.git
synced 2026-11-28 20:22:39 +00:00
feat(mobile): tag escaped relay errors with their call and reason class (#9821)
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>
This commit is contained in:
@@ -42,6 +42,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat
|
||||
- **The reporting destination is a build-time setting**, named with the implementation to match the existing `BUZZ_` build settings. When it is absent, the app uses the do-nothing implementation and never initializes the SDK. There is no check on the kind of build, no in-app switch and no notice ([ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md)).
|
||||
- **Crashes and uncaught errors** are captured by the SDK's own handlers for native crashes, Flutter framework errors and uncaught asynchronous Dart errors, installed at startup around the app.
|
||||
- **Explicit error reports** are added at the places where the app meets something that should never happen: a relay frame or query response that cannot be decoded, a relay rejection whose reason says the app sent something invalid (except a refusal the app already handles as an expected outcome, such as an archived channel, an Unarchive of a channel that is no longer archived, a channel name that is taken, an agent whose policy refuses the addition, a guest adding people, a sole owner leaving or an event whose timestamp is outside the relay's window, which is counted; that last one is left out for every event, so a device with a wrong clock does not report every publish, at the cost of hiding a signed event retried after the window has passed), an account or push gateway response that cannot be understood, saved data that cannot be read back, and an event subscriber that throws while handling an event.
|
||||
- **Escaped relay errors say which call failed and why.** An error from a relay call that nothing catches reaches the SDK on its own, not through the reporting module, and its text is removed, so on its own it would say only that some call failed. The relay's errors therefore carry the call (publish, query, history or subscribe) and a reason class as fixed values, and a report of one is tagged `relay.call` and `relay.reason`. The reason class is the relay's reason prefix (invalid, rate-limited, restricted, auth-required, blocked, duplicate, pow, unsupported or error), `timeout` when the call timed out in the app before the relay answered, and `other` for any other prefix. Never the relay's own text. The report is also grouped by call and reason, on top of the usual grouping by stack, so a rate limit and an invalid request from one place are separate issues. A publish, history request or live subscription keeps the stack of the code that made the call and gives it to the errors it completes later from a timer or socket callback, so the report's stack reaches app code instead of stopping in the SDK's error handler. Queries do the same for their timeouts.
|
||||
- **Routine failures are counted, never reported.** Timeouts, disconnects, unreachable or insecure hosts, rate limits, refused or expired sign-ins and server errors increment a count. That includes the relay's own errors, such as a query that timed out or too many subscriptions. Of the reasons a relay gives for a rejection, only the one that marks the request as invalid is reported, with the exception above; every other reason is counted.
|
||||
- **Networking measurements.** Every request through the app's shared HTTP client and every relay connection event (connected, disconnected, reconnect attempt, request timed out, subscription closed by the relay) is counted with four attributes: backend, endpoint, outcome and kind of failure. The backend is the host name of the server the app was talking to when it is one of the app's own (a relay the app has used this run, the build's Builderlab and push gateway); any other host, such as a remote image's, is counted as `external`, so a host that names a person never leaves the phone. Endpoints are names from a fixed list, never raw paths. Durations are recorded for requests (to response headers), for time to connect, for opening a channel (from asking for its newest history to showing it, first load only, including any wait for a reconnect in between; one that spans a move to the background or starts in the background is not counted, since it measured the time away, and the load after the return is a new open; one that started for another member or community is not counted; one the member backed out of still is, since the load took that long, unless they left while a lost connection was still reconnecting, before the history was asked for again; after a failed open, a retry counts as a new open; a refusal before the history was asked for counts as a failed open with no duration) and for recovering a lost relay connection (from the last frame the lost connection delivered to the next authenticated one, so time spent not noticing a dead socket counts; a quiet connection is taken to have been alive until two ping intervals before the loss, since pongs are not visible to the app, so an idle connection that closes cleanly can read up to a minute long; a loss in the background, or one followed by a move to the background, is not counted; a loss within the first seconds after a return from a brief stay in the background can reach back to before the stay, by at most the same minute). These two durations run on a monotonic clock, so a correction of the device's clock does not move them. A request the app gives up on at its own deadline is a timeout, including one whose successful response body is still arriving; one the app cancels (a view closing, an image scrolled away) is not counted. A request still in flight when the member signs out or switches is not counted for anyone. HTTP is measured where the app's shared HTTP client already classifies transport failures; relay connections are measured by hand in the relay session, since the SDK documents no WebSocket instrumentation.
|
||||
- **Counts are handed to the SDK as they happen**, including while the network is down. The app does no buffering of its own, and the SDK's default limit on unsent data is kept. Accepted consequence: in a long outage the oldest unsent reports can be dropped.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
||||
import 'diagnostic_reporter.dart';
|
||||
import 'relay_error_tags.dart';
|
||||
|
||||
/// The one filter every Dart report, breadcrumb and count passes through
|
||||
/// before it leaves the device. Reports the native SDKs capture themselves
|
||||
@@ -141,11 +142,14 @@ abstract final class DiagnosticFilter {
|
||||
key == installIdTag ||
|
||||
_sdkAttributePrefixes.any(key.startsWith);
|
||||
|
||||
/// The app tags a report with where it came from and which installation
|
||||
/// sent it; the SDK tags it with its origin and environment.
|
||||
/// The app tags a report with where it came from, which installation sent
|
||||
/// it and, for a relay error, the call and reason class; the SDK tags it
|
||||
/// with its origin and environment.
|
||||
static bool _allowsTag(String key) =>
|
||||
key == 'operation' ||
|
||||
key == installIdTag ||
|
||||
key == RelayErrorTags.callTag ||
|
||||
key == RelayErrorTags.reasonTag ||
|
||||
key.startsWith('event.') ||
|
||||
allowsAttribute(key);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import 'package:uuid/uuid.dart';
|
||||
import '../http/app_http_client.dart';
|
||||
import 'diagnostic_filter.dart';
|
||||
import 'diagnostic_reporter.dart';
|
||||
import 'relay_error_tags.dart';
|
||||
import 'sentry_diagnostic_reporter.dart';
|
||||
|
||||
/// The build's reporting destination, a Sentry DSN supplied at build time.
|
||||
@@ -151,7 +152,8 @@ void configureDiagnostics(SentryFlutterOptions options, String destination) {
|
||||
..enableAppHangTracking = true
|
||||
..anrEnabled = true
|
||||
..enableWatchdogTerminationTracking = true
|
||||
..beforeSend = ((event, hint) => DiagnosticFilter.filterEvent(event))
|
||||
..beforeSend = ((event, hint) =>
|
||||
DiagnosticFilter.filterEvent(RelayErrorTags.apply(event)))
|
||||
..beforeBreadcrumb = ((crumb, hint) =>
|
||||
DiagnosticFilter.filterBreadcrumb(crumb))
|
||||
..beforeSendMetric = ((metric, hint) =>
|
||||
|
||||
35
mobile/lib/shared/diagnostics/relay_error_tags.dart
Normal file
35
mobile/lib/shared/diagnostics/relay_error_tags.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
||||
import '../relay/relay_call_error.dart';
|
||||
|
||||
/// Says which relay call an error came from and why it failed, on a report
|
||||
/// whose error is a [RelayCallError].
|
||||
///
|
||||
/// An error that escapes uncaught reaches the SDK from the zone's handler,
|
||||
/// not through the reporter, and the filter replaces its text, so without
|
||||
/// this a report of one says only that some relay call failed. The reason is
|
||||
/// the relay's reason prefix or a timeout, never the relay's own text.
|
||||
abstract final class RelayErrorTags {
|
||||
/// Tag naming the relay call: publish, query, history or subscribe.
|
||||
static const callTag = 'relay.call';
|
||||
|
||||
/// Tag naming the reason class, such as invalid or rate-limited.
|
||||
static const reasonTag = 'relay.reason';
|
||||
|
||||
/// Adds the tags to [event], and splits its issue by call and reason on top
|
||||
/// of the usual grouping by stack, so a rate limit and an invalid request
|
||||
/// from the same call site are not one issue. Other events pass unchanged.
|
||||
static SentryEvent apply(SentryEvent event) {
|
||||
final error = event.throwable;
|
||||
if (error is! RelayCallError) return event;
|
||||
final call = error.call.name;
|
||||
final reason = error.reason.tag;
|
||||
event.tags = {...?event.tags, callTag: call, reasonTag: reason};
|
||||
event.fingerprint = [
|
||||
SentryEvent.defaultFingerprint,
|
||||
'relay.call:$call',
|
||||
'relay.reason:$reason',
|
||||
];
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ export 'media_image.dart';
|
||||
export 'media_upload.dart';
|
||||
export 'nostr_filters.dart';
|
||||
export 'nostr_models.dart';
|
||||
export 'relay_call_error.dart';
|
||||
export 'relay_closed_policy.dart';
|
||||
export 'relay_error_text.dart';
|
||||
export 'relay_client.dart';
|
||||
|
||||
108
mobile/lib/shared/relay/relay_call_error.dart
Normal file
108
mobile/lib/shared/relay/relay_call_error.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
import 'dart:async';
|
||||
|
||||
/// The relay call an error came from.
|
||||
enum RelayCall {
|
||||
/// An EVENT sent over the socket and acknowledged with OK.
|
||||
publish,
|
||||
|
||||
/// A one-shot query over the relay's HTTP bridge.
|
||||
query,
|
||||
|
||||
/// A one-shot REQ over the socket, read until EOSE.
|
||||
history,
|
||||
|
||||
/// A live REQ, up to its first EOSE.
|
||||
subscribe,
|
||||
}
|
||||
|
||||
/// The reason class of a failed relay call: the relay's own reason prefix, or
|
||||
/// a timeout. Never the reason text, which is free-form and can quote what
|
||||
/// the app sent.
|
||||
enum RelayReason {
|
||||
invalid('invalid'),
|
||||
rateLimited('rate-limited'),
|
||||
restricted('restricted'),
|
||||
authRequired('auth-required'),
|
||||
blocked('blocked'),
|
||||
duplicate('duplicate'),
|
||||
pow('pow'),
|
||||
unsupported('unsupported'),
|
||||
error('error'),
|
||||
|
||||
/// The call timed out here, before the relay answered.
|
||||
timeout('timeout'),
|
||||
|
||||
/// A reason with no known prefix.
|
||||
other('other');
|
||||
|
||||
const RelayReason(this.tag);
|
||||
|
||||
/// The wording that leaves the device.
|
||||
final String tag;
|
||||
|
||||
static final _prefixes = {
|
||||
for (final reason in values)
|
||||
if (reason != timeout && reason != other) reason.tag: reason,
|
||||
};
|
||||
|
||||
/// The class of a relay `OK` or `CLOSED` [message]: its prefix, up to the
|
||||
/// first colon, when that is one of the relay's.
|
||||
static RelayReason fromMessage(String message) {
|
||||
final colon = message.indexOf(':');
|
||||
if (colon < 0) return other;
|
||||
return _prefixes[message.substring(0, colon).trim().toLowerCase()] ?? other;
|
||||
}
|
||||
|
||||
/// The class of an HTTP error [status] from the relay's `/query`. Its body
|
||||
/// is not read: the status alone says rate limit, refusal or server error.
|
||||
static RelayReason fromHttpStatus(int status) => switch (status) {
|
||||
429 => rateLimited,
|
||||
401 => authRequired,
|
||||
403 => restricted,
|
||||
>= 500 && < 600 => error,
|
||||
_ => other,
|
||||
};
|
||||
}
|
||||
|
||||
/// An error from a relay call that says which call and why.
|
||||
///
|
||||
/// Diagnostic reports of these carry [call] and [reason] as tags, because the
|
||||
/// error's own text is removed before a report leaves the device.
|
||||
abstract interface class RelayCallError implements Exception {
|
||||
RelayCall get call;
|
||||
RelayReason get reason;
|
||||
}
|
||||
|
||||
/// A relay call timed out before the relay answered.
|
||||
class RelayTimeoutException extends TimeoutException implements RelayCallError {
|
||||
RelayTimeoutException(this.call, String message, [Duration? duration])
|
||||
: super(message, duration);
|
||||
|
||||
@override
|
||||
final RelayCall call;
|
||||
|
||||
@override
|
||||
RelayReason get reason => RelayReason.timeout;
|
||||
|
||||
/// The text without the duration, which [message] already states. Screens
|
||||
/// show this text.
|
||||
@override
|
||||
String toString() => 'TimeoutException: $message';
|
||||
}
|
||||
|
||||
/// The relay closed a history or live subscription with [message].
|
||||
class RelayClosedException implements RelayCallError {
|
||||
RelayClosedException(this.call, this.message);
|
||||
|
||||
@override
|
||||
final RelayCall call;
|
||||
|
||||
/// The relay's `CLOSED` reason. Callers read its text.
|
||||
final String message;
|
||||
|
||||
@override
|
||||
RelayReason get reason => RelayReason.fromMessage(message);
|
||||
|
||||
@override
|
||||
String toString() => 'Exception: $message';
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:buzz/shared/http/app_http_client.dart';
|
||||
import 'relay_call_error.dart';
|
||||
|
||||
/// Lightweight HTTP context for talking to the Buzz relay.
|
||||
///
|
||||
@@ -46,3 +47,18 @@ class RelayException implements Exception {
|
||||
return 'RelayException($statusCode): $trimmedBody';
|
||||
}
|
||||
}
|
||||
|
||||
/// The relay's `/query` answered with a non-2xx status.
|
||||
///
|
||||
/// Callers that retry, fall back or give up read the [RelayException] status
|
||||
/// and body as before. A diagnostic report of one is tagged with the call and
|
||||
/// a reason class taken from the status alone, never the body.
|
||||
class RelayQueryException extends RelayException implements RelayCallError {
|
||||
RelayQueryException(super.statusCode, super.body);
|
||||
|
||||
@override
|
||||
RelayCall get call => RelayCall.query;
|
||||
|
||||
@override
|
||||
RelayReason get reason => RelayReason.fromHttpStatus(statusCode);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ 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;
|
||||
|
||||
@@ -38,6 +39,18 @@ class RelayHttpQueryClient {
|
||||
_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,
|
||||
@@ -45,6 +58,7 @@ class RelayHttpQueryClient {
|
||||
required Duration timeout,
|
||||
http.Client Function(http.Client, bool Function())? decorate,
|
||||
}) async {
|
||||
final callSite = StackTrace.current;
|
||||
final generation = _injectedClient == null
|
||||
? (_currentGeneration ??= _createGeneration())
|
||||
: null;
|
||||
@@ -73,7 +87,7 @@ class RelayHttpQueryClient {
|
||||
_currentGeneration = null;
|
||||
}
|
||||
generation?.retire();
|
||||
rethrow;
|
||||
Error.throwWithStackTrace(_timedOut(timeout, RelayCall.query), callSite);
|
||||
} finally {
|
||||
active = false;
|
||||
generation?.release();
|
||||
@@ -81,13 +95,16 @@ class RelayHttpQueryClient {
|
||||
}
|
||||
|
||||
/// Sends a non-redirecting request, bounding bytes before buffering or parsing.
|
||||
/// The deadline includes headers and the entire response body.
|
||||
/// 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 =
|
||||
@@ -145,7 +162,7 @@ class RelayHttpQueryClient {
|
||||
_currentGeneration = null;
|
||||
}
|
||||
generation?.retire();
|
||||
rethrow;
|
||||
Error.throwWithStackTrace(_timedOut(timeout, call), callSite);
|
||||
} finally {
|
||||
finished = true;
|
||||
// Cancelling an iterator that never listened leaves the body
|
||||
|
||||
@@ -19,6 +19,7 @@ import '../hosted/hosted_relay_auth.dart';
|
||||
import '../hosted/builderlab_account.dart';
|
||||
import 'nostr_filters.dart';
|
||||
import 'nostr_models.dart';
|
||||
import 'relay_call_error.dart';
|
||||
import 'relay_client.dart';
|
||||
import 'relay_closed_policy.dart';
|
||||
import 'relay_http_query_client.dart';
|
||||
@@ -297,7 +298,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
response.headers['content-type'],
|
||||
);
|
||||
_activateRateLimitGateFromHttpError(body);
|
||||
throw RelayException(response.statusCode, body);
|
||||
throw RelayQueryException(response.statusCode, body);
|
||||
}
|
||||
// Decoding runs off the UI isolate, so the session can retire meanwhile.
|
||||
// A retired session reports that, not whatever its bytes decoded to.
|
||||
@@ -343,9 +344,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
failure: NetworkFailure.timeout,
|
||||
since: sub.startedAt,
|
||||
);
|
||||
sub.completer.completeError(
|
||||
TimeoutException('Relay history request timed out after $timeout'),
|
||||
);
|
||||
sub.timedOut(timeout);
|
||||
}
|
||||
if (sub?.heldFilter == null) _sendClose(subId);
|
||||
});
|
||||
@@ -476,11 +475,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
failure: NetworkFailure.timeout,
|
||||
since: pending.startedAt,
|
||||
);
|
||||
pending.completer.completeError(
|
||||
RelayAckTimeoutError(
|
||||
'Event ${event.id} not acknowledged within $timeout',
|
||||
),
|
||||
);
|
||||
pending.timedOut(event.id, timeout);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -922,7 +917,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
failure: _relayMessageFailure(message),
|
||||
since: historySub.startedAt,
|
||||
);
|
||||
historySub.completer.completeError(Exception(message));
|
||||
historySub.fail(RelayClosedException(RelayCall.history, message));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -943,7 +938,10 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
if (closedClass == RelayClosedClass.terminal &&
|
||||
!isRelayDeadlineError(message)) {
|
||||
if (readyCompleter != null && !readyCompleter.isCompleted) {
|
||||
readyCompleter.completeError(Exception(message));
|
||||
readyCompleter.completeError(
|
||||
RelayClosedException(RelayCall.subscribe, message),
|
||||
liveSub.callSite,
|
||||
);
|
||||
}
|
||||
liveSub.onClosed?.call(message);
|
||||
_removeLiveSubscription(subId, liveSub);
|
||||
@@ -1066,7 +1064,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
_rateLimitGate.activate(parseRateLimitRetrySeconds(message));
|
||||
}
|
||||
if (!pending.completer.isCompleted) {
|
||||
pending.completer.completeError(
|
||||
pending.fail(
|
||||
RelayEventRejectedException(
|
||||
message.isNotEmpty ? message : 'Event rejected',
|
||||
),
|
||||
@@ -1148,7 +1146,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
for (final entry in _historySubscriptions.values) {
|
||||
entry.timeout.cancel();
|
||||
if (!entry.completer.isCompleted) {
|
||||
entry.completer.completeError(error ?? Exception('Connection lost'));
|
||||
entry.fail(error ?? Exception('Connection lost'));
|
||||
}
|
||||
}
|
||||
_historySubscriptions.clear();
|
||||
@@ -1158,7 +1156,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
|
||||
for (final entry in _pendingEvents.values) {
|
||||
entry.timeout.cancel();
|
||||
if (!entry.completer.isCompleted) {
|
||||
entry.completer.completeError(RelayAckLostError(error));
|
||||
entry.fail(RelayAckLostError(error));
|
||||
}
|
||||
}
|
||||
_pendingEvents.clear();
|
||||
|
||||
@@ -24,11 +24,17 @@ extension on RelaySessionNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<http.Response> send(http.Request request, int maxBytes) async {
|
||||
// Only the `/query` POST is a [RelayCall.query]; the discovery GET is not.
|
||||
Future<http.Response> send(
|
||||
http.Request request,
|
||||
int maxBytes, {
|
||||
bool query = false,
|
||||
}) async {
|
||||
final response = await _httpQueryClient.sendBounded(
|
||||
request,
|
||||
maxBytes: maxBytes,
|
||||
timeout: timeout,
|
||||
call: query ? RelayCall.query : null,
|
||||
decorate: (client, active) => HostedRelayHttpClient(
|
||||
_snapshotAuth,
|
||||
config,
|
||||
@@ -45,7 +51,9 @@ extension on RelaySessionNotifier {
|
||||
maxInflatedBytes: maxBytes,
|
||||
);
|
||||
_activateRateLimitGateFromHttpError(text);
|
||||
throw RelayException(response.statusCode, text);
|
||||
throw query
|
||||
? RelayQueryException(response.statusCode, text)
|
||||
: RelayException(response.statusCode, text);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -91,7 +99,11 @@ extension on RelaySessionNotifier {
|
||||
nsec: nsec,
|
||||
),
|
||||
});
|
||||
final response = await send(request, readStateSnapshotMaxEnvelopeBytes);
|
||||
final response = await send(
|
||||
request,
|
||||
readStateSnapshotMaxEnvelopeBytes,
|
||||
query: true,
|
||||
);
|
||||
// Inflating, parsing and Schnorr verification must not block Flutter's
|
||||
// UI isolate.
|
||||
final List<NostrEvent> events;
|
||||
|
||||
@@ -6,6 +6,20 @@ class _HistorySubscription {
|
||||
final Timer timeout;
|
||||
final DateTime startedAt;
|
||||
|
||||
/// Where the call was made. Errors completed later, from a timer or a
|
||||
/// socket callback, carry it, so an escaped error's stack reaches the caller.
|
||||
final StackTrace callSite = StackTrace.current;
|
||||
|
||||
void fail(Object error) => completer.completeError(error, callSite);
|
||||
|
||||
void timedOut(Duration timeout) => fail(
|
||||
RelayTimeoutException(
|
||||
RelayCall.history,
|
||||
'Relay history request timed out after $timeout',
|
||||
timeout,
|
||||
),
|
||||
);
|
||||
|
||||
/// The filter of a request held until the socket authenticates.
|
||||
NostrFilter? heldFilter;
|
||||
|
||||
@@ -25,6 +39,11 @@ class _LiveSubscription {
|
||||
/// Whether a replay narrows [filter] with a `since` from what this
|
||||
/// subscription last saw.
|
||||
final bool resumeSince;
|
||||
|
||||
/// Where the call was made. Errors completed later, from a timer or a
|
||||
/// socket callback, carry it, so an escaped error's stack reaches the caller.
|
||||
final StackTrace callSite = StackTrace.current;
|
||||
|
||||
Completer<void>? readyCompleter;
|
||||
int? lastSeenCreatedAt;
|
||||
|
||||
@@ -78,6 +97,19 @@ class _PendingEvent {
|
||||
final Timer timeout;
|
||||
final DateTime startedAt;
|
||||
|
||||
/// Where the call was made. Errors completed later, from a timer or a
|
||||
/// socket callback, carry it, so an escaped error's stack reaches the caller.
|
||||
final StackTrace callSite = StackTrace.current;
|
||||
|
||||
void fail(Object error) => completer.completeError(error, callSite);
|
||||
|
||||
void timedOut(String eventId, Duration timeout) => fail(
|
||||
RelayAckTimeoutError(
|
||||
'Event $eventId not acknowledged within $timeout',
|
||||
timeout,
|
||||
),
|
||||
);
|
||||
|
||||
_PendingEvent({
|
||||
required this.completer,
|
||||
required this.timeout,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'relay_call_error.dart';
|
||||
import 'relay_socket.dart';
|
||||
|
||||
enum SessionStatus { disconnected, connecting, connected, reconnecting }
|
||||
@@ -40,9 +39,10 @@ class RelayNotConnectedError extends StateError {
|
||||
|
||||
/// The relay did not acknowledge a published EVENT in time, so it may or may
|
||||
/// not have accepted it. Other relay timeouts (history, queries) happen before
|
||||
/// anything is published and stay plain [TimeoutException]s.
|
||||
class RelayAckTimeoutError extends TimeoutException {
|
||||
RelayAckTimeoutError(super.message, [super.duration]);
|
||||
/// anything is published and are plain [RelayTimeoutException]s.
|
||||
class RelayAckTimeoutError extends RelayTimeoutException {
|
||||
RelayAckTimeoutError(String message, [Duration? duration])
|
||||
: super(RelayCall.publish, message, duration);
|
||||
}
|
||||
|
||||
/// The connection ended after an EVENT was sent but before the relay
|
||||
|
||||
@@ -9,6 +9,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
|
||||
import '../diagnostics/diagnostic_reporter.dart';
|
||||
import 'nostr_models.dart';
|
||||
import 'relay_call_error.dart';
|
||||
import 'relay_websocket.dart';
|
||||
import 'package:buzz/shared/crypto/event_signing.dart';
|
||||
|
||||
@@ -30,11 +31,17 @@ class RelayAuthRejectedException implements Exception {
|
||||
}
|
||||
|
||||
/// The relay answered an EVENT with OK false, so it wasn't stored.
|
||||
class RelayEventRejectedException implements Exception {
|
||||
class RelayEventRejectedException implements RelayCallError {
|
||||
final String message;
|
||||
|
||||
const RelayEventRejectedException(this.message);
|
||||
|
||||
@override
|
||||
RelayCall get call => RelayCall.publish;
|
||||
|
||||
@override
|
||||
RelayReason get reason => RelayReason.fromMessage(message);
|
||||
|
||||
@override
|
||||
String toString() => 'Exception: $message';
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:nostr/nostr.dart' as nostr;
|
||||
|
||||
import '../diagnostics/diagnostic_reporter.dart';
|
||||
import 'nostr_models.dart';
|
||||
import 'relay_call_error.dart';
|
||||
import 'relay_closed_policy.dart';
|
||||
import 'relay_session.dart';
|
||||
import 'relay_socket.dart';
|
||||
@@ -96,6 +97,9 @@ Future<NostrEvent> submitSignedEventOnce({
|
||||
// push tombstone; its reports must not name the active member.
|
||||
final reporter = SignerDiagnosticReporter(diagnostics, signer: event.pubkey);
|
||||
final result = Completer<NostrEvent>();
|
||||
// Errors completed later, from a socket callback or timer, carry the stack
|
||||
// of the caller, so an escaped error's report reaches app code.
|
||||
final callSite = StackTrace.current;
|
||||
late final RelaySocket socket;
|
||||
socket = RelaySocket(
|
||||
wsUrl: wsUrl,
|
||||
@@ -128,24 +132,70 @@ Future<NostrEvent> submitSignedEventOnce({
|
||||
operation: DiagnosticOperation.relayRejection,
|
||||
);
|
||||
}
|
||||
result.completeError(Exception('Relay rejected event: $detail'));
|
||||
result.completeError(_SignedEventRejection(detail), callSite);
|
||||
}
|
||||
}
|
||||
},
|
||||
onConnected: () => socket.send(['EVENT', event.toJson()]),
|
||||
onConnected: () {
|
||||
if (!result.isCompleted) socket.send(['EVENT', event.toJson()]);
|
||||
},
|
||||
onDisconnected: (error) {
|
||||
if (!result.isCompleted) {
|
||||
result.completeError(error ?? Exception('Relay disconnected'));
|
||||
if (result.isCompleted) return;
|
||||
// The socket's own authentication deadline is shorter than [timeout],
|
||||
// so its plain timeout is typed here as this call's.
|
||||
if (error is TimeoutException && error is! RelayCallError) {
|
||||
result.completeError(
|
||||
RelayTimeoutException(
|
||||
RelayCall.publish,
|
||||
error.message ?? 'Relay did not answer',
|
||||
error.duration,
|
||||
),
|
||||
callSite,
|
||||
);
|
||||
return;
|
||||
}
|
||||
result.completeError(error ?? Exception('Relay disconnected'), callSite);
|
||||
},
|
||||
);
|
||||
socket.headers = headers;
|
||||
socket.diagnostics = reporter;
|
||||
final resultFuture = result.future.timeout(timeout);
|
||||
// The deadline covers connecting and authenticating too. Once it passes the
|
||||
// event is never sent, and its timeout goes to the caller, never to the
|
||||
// zone as an uncaught error.
|
||||
final deadline = Timer(timeout, () {
|
||||
if (result.isCompleted) return;
|
||||
result.completeError(
|
||||
RelayTimeoutException(
|
||||
RelayCall.publish,
|
||||
'Relay did not answer within $timeout',
|
||||
timeout,
|
||||
),
|
||||
callSite,
|
||||
);
|
||||
});
|
||||
try {
|
||||
await socket.connect();
|
||||
return await resultFuture;
|
||||
// Whichever settles first: a failed connect, or the result (which the
|
||||
// deadline settles if nothing else does). Future.any listens to both, so
|
||||
// the other one's later error is not uncaught.
|
||||
return await Future.any([
|
||||
socket.connect().then((_) => result.future),
|
||||
result.future,
|
||||
]);
|
||||
} finally {
|
||||
deadline.cancel();
|
||||
await socket.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/// The relay answered a one-shot EVENT with OK false and [detail]. Its text
|
||||
/// names the refusal for callers; its reason class is the prefix of [detail].
|
||||
class _SignedEventRejection extends RelayEventRejectedException {
|
||||
_SignedEventRejection(String detail)
|
||||
: _reason = RelayReason.fromMessage(detail),
|
||||
super('Relay rejected event: $detail');
|
||||
|
||||
final RelayReason _reason;
|
||||
|
||||
@override
|
||||
RelayReason get reason => _reason;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import 'package:buzz/shared/diagnostics/diagnostic_member_binding.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_startup.dart';
|
||||
import 'package:buzz/shared/diagnostics/sentry_diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/relay/relay_provider.dart';
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -318,6 +318,89 @@ void main() {
|
||||
expect(transport.events, hasLength(2));
|
||||
});
|
||||
|
||||
group('an error that escapes from a relay call', () {
|
||||
Future<Map<String, dynamic>> escaped(Object error) async {
|
||||
// As an uncaught asynchronous error reaches the SDK: straight to the
|
||||
// hub, not through the app's reporter.
|
||||
await hub.captureException(error, stackTrace: StackTrace.current);
|
||||
return transport.events.single;
|
||||
}
|
||||
|
||||
test(
|
||||
'is tagged with the call and the reason class, not the text',
|
||||
() async {
|
||||
final sent = await escaped(
|
||||
const RelayEventRejectedException('rate-limited: private-marker'),
|
||||
);
|
||||
|
||||
expect(sent['tags']['relay.call'], 'publish');
|
||||
expect(sent['tags']['relay.reason'], 'rate-limited');
|
||||
expect(jsonEncode(sent), isNot(contains('private-marker')));
|
||||
final exception = (sent['exception']['values'] as List).last as Map;
|
||||
expect(exception['type'], 'RelayEventRejectedException');
|
||||
expect(exception['value'], DiagnosticFilter.removedText);
|
||||
},
|
||||
);
|
||||
|
||||
test('is grouped by call and reason on top of its stack', () async {
|
||||
final sent = await escaped(
|
||||
RelayClosedException(RelayCall.history, 'error: private-marker'),
|
||||
);
|
||||
|
||||
expect(sent['tags']['relay.call'], 'history');
|
||||
expect(sent['tags']['relay.reason'], 'error');
|
||||
expect(sent['fingerprint'], [
|
||||
'{{ default }}',
|
||||
'relay.call:history',
|
||||
'relay.reason:error',
|
||||
]);
|
||||
});
|
||||
|
||||
test('names a timeout as one', () async {
|
||||
final sent = await escaped(
|
||||
RelayTimeoutException(RelayCall.query, 'private-marker'),
|
||||
);
|
||||
|
||||
expect(sent['tags']['relay.call'], 'query');
|
||||
expect(sent['tags']['relay.reason'], 'timeout');
|
||||
expect(jsonEncode(sent), isNot(contains('private-marker')));
|
||||
});
|
||||
|
||||
test('with an unknown prefix has the reason other', () async {
|
||||
final sent = await escaped(
|
||||
const RelayEventRejectedException('teapot: private-marker'),
|
||||
);
|
||||
|
||||
expect(sent['tags']['relay.reason'], 'other');
|
||||
expect(jsonEncode(sent), isNot(contains('private-marker')));
|
||||
});
|
||||
|
||||
test('is tagged when reported through the reporter too', () async {
|
||||
SentryDiagnosticReporter(hub: hub).reportError(
|
||||
const RelayEventRejectedException('invalid: private-marker'),
|
||||
StackTrace.current,
|
||||
operation: DiagnosticOperation.relayRejection,
|
||||
);
|
||||
await transport.first();
|
||||
|
||||
final sent = transport.events.single;
|
||||
expect(sent['tags']['operation'], 'relayRejection');
|
||||
expect(sent['tags']['relay.call'], 'publish');
|
||||
expect(sent['tags']['relay.reason'], 'invalid');
|
||||
});
|
||||
|
||||
test(
|
||||
'is the only kind of error that gets the tags or the grouping',
|
||||
() async {
|
||||
final sent = await escaped(StateError('private-marker'));
|
||||
|
||||
expect(sent['tags'], isNot(contains('relay.call')));
|
||||
expect(sent['tags'], isNot(contains('relay.reason')));
|
||||
expect(sent, isNot(contains('fingerprint')));
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('sends only the allowed contexts', (tester) async {
|
||||
tester.platformDispatcher.accessibilityFeaturesTestValue =
|
||||
const FakeAccessibilityFeatures(accessibleNavigation: true);
|
||||
|
||||
315
mobile/test/shared/diagnostics/relay_refusal_report_test.dart
Normal file
315
mobile/test/shared/diagnostics/relay_refusal_report_test.dart
Normal file
@@ -0,0 +1,315 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:buzz/shared/auth/auth_provider.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_startup.dart';
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:nostr/nostr.dart' as nostr;
|
||||
import 'package:sentry_flutter/sentry_flutter.dart';
|
||||
|
||||
/// Refusals produced by the relay code itself, reported the way an uncaught
|
||||
/// error reaches the SDK, and read back as the serialized event.
|
||||
void main() {
|
||||
late _MemoryTransport transport;
|
||||
late Hub hub;
|
||||
|
||||
setUp(() {
|
||||
transport = _MemoryTransport();
|
||||
final options = SentryFlutterOptions();
|
||||
configureDiagnostics(options, 'https://key@example.org/1');
|
||||
options
|
||||
..transport = transport
|
||||
..sendClientReports = false;
|
||||
hub = Hub(options);
|
||||
});
|
||||
tearDown(() => hub.close());
|
||||
|
||||
Future<Map<String, dynamic>> escaped(Object error, StackTrace stack) async {
|
||||
await hub.captureException(error, stackTrace: stack);
|
||||
return transport.events.single;
|
||||
}
|
||||
|
||||
Future<(Object, StackTrace)> failure(Future<Object?> call) async {
|
||||
try {
|
||||
await call;
|
||||
} catch (error, stack) {
|
||||
return (error, stack);
|
||||
}
|
||||
fail('the call succeeded');
|
||||
}
|
||||
|
||||
group('a refused /query', () {
|
||||
final keys = nostr.Keys.generate();
|
||||
const marker = 'private-marker';
|
||||
|
||||
RelaySessionNotifier session(http.Client client) {
|
||||
final session = RelaySessionNotifier(httpClient: client);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
authProvider.overrideWith(_PendingAuth.new),
|
||||
relayConfigProvider.overrideWith(() => _Config(keys.nsec)),
|
||||
relaySessionProvider.overrideWith(() => session),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
container.read(relaySessionProvider);
|
||||
return session;
|
||||
}
|
||||
|
||||
for (final (status, reason) in [
|
||||
(429, 'rate-limited'),
|
||||
(401, 'auth-required'),
|
||||
(403, 'restricted'),
|
||||
(503, 'error'),
|
||||
(400, 'other'),
|
||||
]) {
|
||||
test('$status is tagged query and $reason, without its body', () async {
|
||||
final relay = session(
|
||||
MockClient((_) async => http.Response('{"error":"$marker"}', status)),
|
||||
);
|
||||
|
||||
final (error, stack) = await failure(relay.queryRelay(const []));
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(error, isA<RelayException>());
|
||||
expect((error as RelayException).statusCode, status);
|
||||
expect(error.body, contains(marker));
|
||||
expect(sent['tags']['relay.call'], 'query');
|
||||
expect(sent['tags']['relay.reason'], reason);
|
||||
expect(sent['fingerprint'], [
|
||||
'{{ default }}',
|
||||
'relay.call:query',
|
||||
'relay.reason:$reason',
|
||||
]);
|
||||
expect(jsonEncode(sent), isNot(contains(marker)));
|
||||
});
|
||||
}
|
||||
|
||||
group('of the read state snapshot', () {
|
||||
final discovery = jsonEncode({
|
||||
'read_state_snapshot': {
|
||||
'version': 1,
|
||||
'community_id': 'abcdabcd-eeee-abcd-abcd-abcdefabcdef',
|
||||
'max_events': 4096,
|
||||
'max_event_array_bytes': 8 * 1024 * 1024,
|
||||
},
|
||||
});
|
||||
|
||||
test('is tagged query and its reason, without its body', () async {
|
||||
final relay = session(
|
||||
MockClient(
|
||||
(request) async => request.method == 'GET'
|
||||
? http.Response(discovery, 200)
|
||||
: http.Response('{"error":"$marker"}', 429),
|
||||
),
|
||||
);
|
||||
|
||||
final (error, stack) = await failure(relay.fetchReadStateSnapshot());
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect((error as RelayException).statusCode, 429);
|
||||
expect(sent['tags']['relay.call'], 'query');
|
||||
expect(sent['tags']['relay.reason'], 'rate-limited');
|
||||
expect(jsonEncode(sent), isNot(contains(marker)));
|
||||
});
|
||||
|
||||
test('discovery is not a query and is not tagged', () async {
|
||||
final relay = session(
|
||||
MockClient((_) async => http.Response('{"error":"$marker"}', 429)),
|
||||
);
|
||||
|
||||
final (error, stack) = await failure(relay.fetchReadStateSnapshot());
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(error, isA<RelayException>());
|
||||
expect(error, isNot(isA<RelayCallError>()));
|
||||
expect(sent['tags'], isNot(contains('relay.call')));
|
||||
expect(jsonEncode(sent), isNot(contains(marker)));
|
||||
});
|
||||
|
||||
test('a stalled discovery is an untyped timeout, not tagged', () async {
|
||||
final relay = session(
|
||||
MockClient((_) => Completer<http.Response>().future),
|
||||
);
|
||||
|
||||
final (error, stack) = await failure(
|
||||
relay.fetchReadStateSnapshot(
|
||||
timeout: const Duration(milliseconds: 50),
|
||||
),
|
||||
);
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(error, isA<TimeoutException>());
|
||||
expect(error, isNot(isA<RelayCallError>()));
|
||||
expect(sent['tags'], isNot(contains('relay.call')));
|
||||
expect(sent['tags'], isNot(contains('relay.reason')));
|
||||
});
|
||||
|
||||
test('a stalled snapshot POST is a query timeout', () async {
|
||||
final relay = session(
|
||||
MockClient(
|
||||
(request) => request.method == 'GET'
|
||||
? Future.value(http.Response(discovery, 200))
|
||||
: Completer<http.Response>().future,
|
||||
),
|
||||
);
|
||||
|
||||
final (error, stack) = await failure(
|
||||
relay.fetchReadStateSnapshot(
|
||||
timeout: const Duration(milliseconds: 50),
|
||||
),
|
||||
);
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(error, isA<RelayTimeoutException>());
|
||||
expect(sent['tags']['relay.call'], 'query');
|
||||
expect(sent['tags']['relay.reason'], 'timeout');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
group('a one-shot signed event', () {
|
||||
const marker = 'private-marker';
|
||||
|
||||
var eventsReceived = 0;
|
||||
|
||||
Future<HttpServer> relayAnswering(
|
||||
String? reason, {
|
||||
bool acknowledgeAuth = true,
|
||||
}) async {
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
server.listen((request) async {
|
||||
final ws = await WebSocketTransformer.upgrade(request);
|
||||
ws.add(jsonEncode(['AUTH', 'challenge']));
|
||||
ws.listen((raw) {
|
||||
final frame = jsonDecode(raw as String) as List<dynamic>;
|
||||
final id = (frame[1] as Map<String, dynamic>)['id'];
|
||||
if (frame[0] == 'AUTH' && acknowledgeAuth) {
|
||||
ws.add(jsonEncode(['OK', id, true, '']));
|
||||
}
|
||||
if (frame[0] == 'EVENT') eventsReceived++;
|
||||
if (frame[0] == 'EVENT' && reason != null) {
|
||||
ws.add(jsonEncode(['OK', id, false, reason]));
|
||||
}
|
||||
});
|
||||
});
|
||||
return server;
|
||||
}
|
||||
|
||||
Future<void> submit(HttpServer server, {Duration? timeout}) =>
|
||||
_submitFromTheCaller(server, timeout: timeout);
|
||||
|
||||
test('refused is tagged publish and the relay prefix, '
|
||||
'with the caller\'s stack and without the relay text', () async {
|
||||
final server = await relayAnswering('rate-limited: $marker');
|
||||
|
||||
final (error, stack) = await failure(submit(server));
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(error, isA<RelayEventRejectedException>());
|
||||
expect(
|
||||
error.toString(),
|
||||
'Exception: Relay rejected event: rate-limited: $marker',
|
||||
);
|
||||
expect((error as RelayCallError).call, RelayCall.publish);
|
||||
expect(error.reason, RelayReason.rateLimited);
|
||||
expect(stack.toString(), contains('_submitFromTheCaller'));
|
||||
expect(sent['tags']['relay.call'], 'publish');
|
||||
expect(sent['tags']['relay.reason'], 'rate-limited');
|
||||
expect(jsonEncode(sent), isNot(contains(marker)));
|
||||
expect(jsonEncode(sent), contains('_submitFromTheCaller'));
|
||||
});
|
||||
|
||||
test('refused with an unknown prefix has the reason other', () async {
|
||||
final server = await relayAnswering('teapot: $marker');
|
||||
|
||||
final (error, stack) = await failure(submit(server));
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(sent['tags']['relay.reason'], 'other');
|
||||
expect(jsonEncode(sent), isNot(contains(marker)));
|
||||
});
|
||||
|
||||
test('unanswered is a publish timeout from the caller', () async {
|
||||
final server = await relayAnswering(null);
|
||||
|
||||
final (error, stack) = await failure(
|
||||
submit(server, timeout: const Duration(milliseconds: 200)),
|
||||
);
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(error, isA<RelayTimeoutException>());
|
||||
expect(stack.toString(), contains('_submitFromTheCaller'));
|
||||
expect(sent['tags']['relay.call'], 'publish');
|
||||
expect(sent['tags']['relay.reason'], 'timeout');
|
||||
});
|
||||
|
||||
test('an authentication the relay never acknowledges is a publish '
|
||||
'timeout from the caller, and the event is never sent', () async {
|
||||
eventsReceived = 0;
|
||||
final server = await relayAnswering(
|
||||
'rate-limited: $marker',
|
||||
acknowledgeAuth: false,
|
||||
);
|
||||
|
||||
// The socket's 8 s authentication deadline passes first.
|
||||
final (error, stack) = await failure(submit(server));
|
||||
final sent = await escaped(error, stack);
|
||||
|
||||
expect(error, isA<TimeoutException>());
|
||||
expect(error, isA<RelayTimeoutException>());
|
||||
expect(stack.toString(), contains('_submitFromTheCaller'));
|
||||
expect(sent['tags']['relay.call'], 'publish');
|
||||
expect(sent['tags']['relay.reason'], 'timeout');
|
||||
expect(jsonEncode(sent), isNot(contains(marker)));
|
||||
expect(eventsReceived, 0);
|
||||
}, timeout: const Timeout(Duration(seconds: 30)));
|
||||
});
|
||||
}
|
||||
|
||||
Future<NostrEvent> _submitFromTheCaller(
|
||||
HttpServer server, {
|
||||
Duration? timeout,
|
||||
}) => submitSignedEventOnce(
|
||||
wsUrl: 'ws://127.0.0.1:${server.port}',
|
||||
nsec: nostr.Keys.generate().nsec,
|
||||
kind: 1,
|
||||
content: '',
|
||||
tags: const [],
|
||||
timeout: timeout ?? const Duration(seconds: 12),
|
||||
);
|
||||
|
||||
class _PendingAuth extends AuthNotifier {
|
||||
@override
|
||||
Future<AuthState> build() => Completer<AuthState>().future;
|
||||
}
|
||||
|
||||
class _Config extends RelayConfigNotifier {
|
||||
_Config(this.nsec);
|
||||
|
||||
final String nsec;
|
||||
|
||||
@override
|
||||
RelayConfig build() =>
|
||||
RelayConfig(baseUrl: 'https://relay.example', nsec: nsec);
|
||||
}
|
||||
|
||||
class _MemoryTransport implements Transport {
|
||||
final events = <Map<String, dynamic>>[];
|
||||
|
||||
@override
|
||||
Future<SentryId?> send(SentryEnvelope envelope) async {
|
||||
for (final item in envelope.items) {
|
||||
if (item.header.type != 'event') continue;
|
||||
final bytes = await item.dataFactory();
|
||||
events.add(jsonDecode(utf8.decode(bytes)) as Map<String, dynamic>);
|
||||
}
|
||||
return envelope.header.eventId;
|
||||
}
|
||||
}
|
||||
133
mobile/test/shared/relay/relay_call_error_test.dart
Normal file
133
mobile/test/shared/relay/relay_call_error_test.dart
Normal file
@@ -0,0 +1,133 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('the reason class of a relay message', () {
|
||||
const cases = {
|
||||
'invalid: bad signature': RelayReason.invalid,
|
||||
'rate-limited: quota exceeded; retry in 4s': RelayReason.rateLimited,
|
||||
'restricted: access revoked': RelayReason.restricted,
|
||||
'auth-required: verification failed': RelayReason.authRequired,
|
||||
'blocked: community policy': RelayReason.blocked,
|
||||
'duplicate: already have this event': RelayReason.duplicate,
|
||||
'pow: insufficient work': RelayReason.pow,
|
||||
'unsupported: filter extension': RelayReason.unsupported,
|
||||
'error: query timed out': RelayReason.error,
|
||||
'INVALID: shouted': RelayReason.invalid,
|
||||
' invalid : padded': RelayReason.invalid,
|
||||
'invalid:': RelayReason.invalid,
|
||||
'timeout: not a relay prefix': RelayReason.other,
|
||||
'other: not a relay prefix': RelayReason.other,
|
||||
'teapot: unknown prefix': RelayReason.other,
|
||||
'no prefix at all': RelayReason.other,
|
||||
'a sentence, then invalid: later': RelayReason.other,
|
||||
'': RelayReason.other,
|
||||
};
|
||||
for (final entry in cases.entries) {
|
||||
test('"${entry.key}" is ${entry.value.name}', () {
|
||||
expect(RelayReason.fromMessage(entry.key), entry.value);
|
||||
});
|
||||
}
|
||||
|
||||
test('the wording that leaves the device is the relay prefix', () {
|
||||
expect(
|
||||
{for (final reason in RelayReason.values) reason.tag},
|
||||
{
|
||||
'invalid',
|
||||
'rate-limited',
|
||||
'restricted',
|
||||
'auth-required',
|
||||
'blocked',
|
||||
'duplicate',
|
||||
'pow',
|
||||
'unsupported',
|
||||
'error',
|
||||
'timeout',
|
||||
'other',
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('the reason class of a /query status', () {
|
||||
const cases = {
|
||||
429: RelayReason.rateLimited,
|
||||
401: RelayReason.authRequired,
|
||||
403: RelayReason.restricted,
|
||||
500: RelayReason.error,
|
||||
503: RelayReason.error,
|
||||
599: RelayReason.error,
|
||||
400: RelayReason.other,
|
||||
404: RelayReason.other,
|
||||
302: RelayReason.other,
|
||||
600: RelayReason.other,
|
||||
};
|
||||
for (final entry in cases.entries) {
|
||||
test('${entry.key} is ${entry.value.name}', () {
|
||||
expect(RelayReason.fromHttpStatus(entry.key), entry.value);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
group('what a relay error says about itself', () {
|
||||
test('a refused query is a relay exception that names the query', () {
|
||||
final error = RelayQueryException(429, '{"error":"slow down"}');
|
||||
|
||||
expect(error, isA<RelayException>());
|
||||
expect(error.call, RelayCall.query);
|
||||
expect(error.reason, RelayReason.rateLimited);
|
||||
expect(error.statusCode, 429);
|
||||
expect(error.toString(), 'RelayException(429): {"error":"slow down"}');
|
||||
});
|
||||
|
||||
test('a rejected publish names the publish and the relay prefix', () {
|
||||
const error = RelayEventRejectedException('blocked: secret reason');
|
||||
|
||||
expect(error.call, RelayCall.publish);
|
||||
expect(error.reason, RelayReason.blocked);
|
||||
expect(error.toString(), 'Exception: blocked: secret reason');
|
||||
});
|
||||
|
||||
test('a closed subscription names its call and keeps its text', () {
|
||||
final error = RelayClosedException(
|
||||
RelayCall.history,
|
||||
'error: query timed out',
|
||||
);
|
||||
|
||||
expect(error.call, RelayCall.history);
|
||||
expect(error.reason, RelayReason.error);
|
||||
expect(error.toString(), 'Exception: error: query timed out');
|
||||
expect(isRelayDeadlineError(error), isTrue);
|
||||
expect(relayErrorMessage(error), 'Query timed out');
|
||||
});
|
||||
|
||||
test('an access refusal is still recognized as one', () {
|
||||
final error = RelayClosedException(
|
||||
RelayCall.subscribe,
|
||||
'restricted: not a member',
|
||||
);
|
||||
|
||||
expect(isRelayAccessDenied(error), isTrue);
|
||||
});
|
||||
|
||||
test('a relay timeout is a timeout of its call', () {
|
||||
final error = RelayTimeoutException(RelayCall.query, 'slow');
|
||||
|
||||
expect(error, isA<TimeoutException>());
|
||||
expect(error.call, RelayCall.query);
|
||||
expect(error.reason, RelayReason.timeout);
|
||||
});
|
||||
|
||||
test('an unacknowledged publish is still a timeout, of the publish', () {
|
||||
final error = RelayAckTimeoutError('no OK', const Duration(seconds: 8));
|
||||
|
||||
expect(error, isA<TimeoutException>());
|
||||
expect(error, isA<RelayTimeoutException>());
|
||||
expect(error.call, RelayCall.publish);
|
||||
expect(error.reason, RelayReason.timeout);
|
||||
expect(error.duration, const Duration(seconds: 8));
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -85,6 +85,7 @@ void main() {
|
||||
http.Request('GET', Uri.parse('https://relay.example/')),
|
||||
maxBytes: 1024,
|
||||
timeout: const Duration(milliseconds: 10),
|
||||
call: null,
|
||||
),
|
||||
throwsA(isA<TimeoutException>()),
|
||||
);
|
||||
@@ -109,6 +110,7 @@ void main() {
|
||||
http.Request('GET', Uri.parse('https://relay.example/')),
|
||||
maxBytes: 1024,
|
||||
timeout: const Duration(seconds: 5),
|
||||
call: null,
|
||||
),
|
||||
throwsA(isA<FormatException>()),
|
||||
);
|
||||
|
||||
@@ -2380,6 +2380,151 @@ void main() {
|
||||
(RelayInvalidRequest, DiagnosticOperation.relayRejection),
|
||||
]);
|
||||
});
|
||||
|
||||
group('errors from relay calls say which call and why', () {
|
||||
test('a rejected publish carries the call and reason class', () async {
|
||||
final session = RelaySessionNotifier();
|
||||
session.debugAttachSocketForTest(_RecordingRelaySocket());
|
||||
|
||||
final publish = session.publish(_event());
|
||||
session.debugHandleMessage([
|
||||
'OK',
|
||||
'event-1',
|
||||
false,
|
||||
'rate-limited: slow down',
|
||||
]);
|
||||
|
||||
await expectLater(
|
||||
publish,
|
||||
throwsA(
|
||||
isA<RelayEventRejectedException>()
|
||||
.having((error) => error.call, 'call', RelayCall.publish)
|
||||
.having(
|
||||
(error) => error.reason,
|
||||
'reason',
|
||||
RelayReason.rateLimited,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('an escaped error keeps the stack of the call', () async {
|
||||
final session = RelaySessionNotifier();
|
||||
session.debugAttachSocketForTest(_RecordingRelaySocket());
|
||||
|
||||
final publish = _publishFromTheCaller(session);
|
||||
session.debugHandleMessage(['OK', 'event-1', false, 'invalid: bad']);
|
||||
|
||||
StackTrace? stack;
|
||||
try {
|
||||
await publish;
|
||||
} on RelayEventRejectedException catch (_, trace) {
|
||||
stack = trace;
|
||||
}
|
||||
expect(stack.toString(), contains('_publishFromTheCaller'));
|
||||
});
|
||||
|
||||
test('an unacknowledged publish is a timeout of the publish', () async {
|
||||
final session = RelaySessionNotifier();
|
||||
session.debugAttachSocketForTest(_RecordingRelaySocket());
|
||||
|
||||
await expectLater(
|
||||
session.publish(_event(), timeout: Duration.zero),
|
||||
throwsA(
|
||||
isA<RelayAckTimeoutError>()
|
||||
.having((error) => error.call, 'call', RelayCall.publish)
|
||||
.having((error) => error.duration, 'duration', Duration.zero)
|
||||
.having(
|
||||
(error) => error.toString(),
|
||||
'text',
|
||||
'TimeoutException: Event event-1 not acknowledged '
|
||||
'within 0:00:00.000000',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('a history timeout is a timeout of the history call', () async {
|
||||
final session = RelaySessionNotifier();
|
||||
|
||||
await expectLater(
|
||||
session.fetchHistory(
|
||||
const NostrFilter(kinds: [39002]),
|
||||
timeout: const Duration(milliseconds: 1),
|
||||
),
|
||||
throwsA(
|
||||
isA<RelayTimeoutException>()
|
||||
.having((error) => error.call, 'call', RelayCall.history)
|
||||
.having((error) => error.reason, 'reason', RelayReason.timeout)
|
||||
.having(
|
||||
(error) => error.toString(),
|
||||
'text',
|
||||
'TimeoutException: Relay history request timed out after '
|
||||
'0:00:00.001000',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('a query timeout is a timeout of the query', () async {
|
||||
final harness = _queryHarness(client: _ControlledHttpClient());
|
||||
addTearDown(harness.container.dispose);
|
||||
|
||||
await expectLater(
|
||||
harness.session.queryRelay(const [], timeout: Duration.zero),
|
||||
throwsA(
|
||||
isA<RelayTimeoutException>().having(
|
||||
(error) => error.call,
|
||||
'call',
|
||||
RelayCall.query,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('a history CLOSED carries the call and the relay prefix', () async {
|
||||
final socket = _RecordingRelaySocket();
|
||||
final session = RelaySessionNotifier();
|
||||
session.debugAttachSocketForTest(socket);
|
||||
|
||||
final history = session.fetchHistory(_channelFilter);
|
||||
session.debugHandleMessage([
|
||||
'CLOSED',
|
||||
_reqs(socket).last[1] as String,
|
||||
'restricted: not a member',
|
||||
]);
|
||||
|
||||
await expectLater(
|
||||
history,
|
||||
throwsA(
|
||||
isA<RelayClosedException>()
|
||||
.having((error) => error.call, 'call', RelayCall.history)
|
||||
.having((error) => error.reason, 'reason', RelayReason.restricted)
|
||||
.having(
|
||||
(error) => error.toString(),
|
||||
'text',
|
||||
'Exception: restricted: not a member',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('a live subscribe CLOSED carries the call', () async {
|
||||
final session = RelaySessionNotifier();
|
||||
|
||||
final subscribe = session.subscribe(_channelFilter, (_) {});
|
||||
session.debugHandleMessage(['CLOSED', 'l-1', 'blocked: no']);
|
||||
|
||||
await expectLater(
|
||||
subscribe,
|
||||
throwsA(
|
||||
isA<RelayClosedException>()
|
||||
.having((error) => error.call, 'call', RelayCall.subscribe)
|
||||
.having((error) => error.reason, 'reason', RelayReason.blocked),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class _ControlledHttpClient extends http.BaseClient {
|
||||
@@ -2562,6 +2707,9 @@ class _FakeRelayConfigNotifier extends RelayConfigNotifier {
|
||||
RelayConfig build() => RelayConfig(baseUrl: _baseUrl, nsec: _nsec);
|
||||
}
|
||||
|
||||
Future<NostrEvent> _publishFromTheCaller(RelaySessionNotifier session) =>
|
||||
session.publish(_event());
|
||||
|
||||
NostrEvent _event({int createdAt = 20, String id = 'event-1'}) {
|
||||
return NostrEvent(
|
||||
id: id,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/relay/relay_call_error.dart';
|
||||
import 'package:buzz/shared/relay/relay_closed_policy.dart';
|
||||
import 'package:buzz/shared/relay/signed_event_relay.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -87,6 +89,51 @@ void main() {
|
||||
]);
|
||||
});
|
||||
}
|
||||
test('a deadline that passes while authenticating reaches the caller, '
|
||||
'and the event is never sent', () async {
|
||||
final events = <Object?>[];
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
server.listen((request) async {
|
||||
final ws = await WebSocketTransformer.upgrade(request);
|
||||
ws.add(jsonEncode(['AUTH', 'challenge']));
|
||||
ws.listen((raw) {
|
||||
final frame = jsonDecode(raw as String) as List<dynamic>;
|
||||
final id = (frame[1] as Map<String, dynamic>)['id'];
|
||||
if (frame[0] == 'EVENT') events.add(id);
|
||||
if (frame[0] == 'AUTH') {
|
||||
// Authentication answers only after the caller's deadline.
|
||||
Timer(const Duration(milliseconds: 600), () {
|
||||
ws.add(jsonEncode(['OK', id, true, '']));
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
final watch = Stopwatch()..start();
|
||||
|
||||
await expectLater(
|
||||
submitSignedEventOnce(
|
||||
wsUrl: 'ws://127.0.0.1:${server.port}',
|
||||
nsec: nostr.Keys.generate().nsec,
|
||||
kind: 1,
|
||||
content: '',
|
||||
tags: const [],
|
||||
timeout: const Duration(milliseconds: 200),
|
||||
),
|
||||
throwsA(
|
||||
isA<RelayTimeoutException>().having(
|
||||
(error) => error.call,
|
||||
'call',
|
||||
RelayCall.publish,
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(watch.elapsed, lessThan(const Duration(milliseconds: 550)));
|
||||
// Outlive the late authentication: an uncaught error would fail the test.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 800));
|
||||
|
||||
expect(events, isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
class _RecordingDiagnostics extends NoopDiagnosticReporter {
|
||||
|
||||
Reference in New Issue
Block a user